Home > Article > Backend Development > How do I sort a Python list in descending order?
Python List Sort in Descending Order
Sorting a list in descending order becomes necessary when you need to prioritize elements based on their magnitude. To achieve this in Python, we delve into the details of the built-in sorting function.
How to Sort a List in Descending Order
Python provides a straightforward way to sort a list in descending order using the sorted() function:
sorted_timestamps = sorted(timestamps, reverse=True)
The reverse argument, set to True, reverses the sorting order, effectively sorting the list in descending order.
Alternatively, you can modify the original list in-place with the sort() method:
timestamps.sort(reverse=True)
Example
Consider the following list of timestamps:
timestamps = [ "2010-04-20 10:07:30", "2010-04-20 10:07:38", "2010-04-20 10:07:52", "2010-04-20 10:08:22", "2010-04-20 10:08:22", "2010-04-20 10:09:46", "2010-04-20 10:10:37", "2010-04-20 10:10:58", "2010-04-20 10:11:50", "2010-04-20 10:12:13", "2010-04-20 10:12:13", "2010-04-20 10:25:38" ]
The sorted version of this list in descending order is:
["2010-04-20 10:25:38", "2010-04-20 10:12:13", "2010-04-20 10:12:13", "2010-04-20 10:11:50", "2010-04-20 10:10:58", "2010-04-20 10:10:37", "2010-04-20 10:09:46", "2010-04-20 10:08:22", "2010-04-20 10:08:22", "2010-04-20 10:07:52", "2010-04-20 10:07:38", "2010-04-20 10:07:30"]
Documentation
For further insights, refer to the official Python documentation on sorting:
The above is the detailed content of How do I sort a Python list in descending order?. For more information, please follow other related articles on the PHP Chinese website!