How to sort a list in descending order in Python
We can use the sort()
function to sort the list in descending order.
Syntax: list.sort(key=..., reverse=...)
- key – function that serves as a key for the sort comparison
- reverse – If
True
, the sorted list is in descending order
It doesn’t return any value. Rather, it changes the original list.
li = [4, 12, 5, 8, 1, 9] li.sort(reverse=True) print("The sorted list: ", li)
Output:
The sorted list: [12, 9, 8, 5, 4, 1]
If you want to return the sorted list rather than change the original list, you can use sorted()
.
li = [4, 12, 5, 8, 1, 9] print("Original list: ",li) print("The sorted list: ", sorted(li, reverse = True))
Output:
Original list: [4, 12, 5, 8, 1, 9] The sorted list: [12, 9, 8, 5, 4, 1]
Subscribe
Login
Please login to comment
0 Discussion