Can a list be sorted in reverse order?


#1

Question

Is it possible to sort() a list but do it in reverse order?

Answer

Yes, you can have the sort() function produce a list sorted in reverse order. The default behavior is to sort from least to greatest amount (depending on whether it is a numeric, string or mixed values). The following code example shows that behavior for list1 which contains only numbers.

list1 = [14, 45, 98, 23, 77, 32, 15, 22, 8, 33, 21, 64]
list1.sort()
print(list1)
# [8, 14, 15, 21, 22, 23, 32, 33, 45, 64, 77, 98]

By using the reverse parameter for sort(), you can change the behavior and have the list sorted in the other direction. This code example shows how to use reverse.

ist1 = [14, 45, 98, 23, 77, 32, 15, 22, 8, 33, 21, 64]
list1.sort(reverse=True)
print(list1)
# [98, 77, 64, 45, 33, 32, 23, 22, 21, 15, 14, 8]