Home >Backend Development >Python Tutorial >How to Sort a List of Timestamps in Descending Order in Python?
Python: Sort a List in Descending Order
Sorting a list in Python is a common task. You may find yourself needing to sort a list of strings, numbers, or even objects. Python provides several methods for sorting lists, and one of them is using the sort() function.
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" ]
To sort this list in descending order, you can use the sort() function with the reverse argument set to True. The reverse argument reverses the order of the sorted elements.
sorted_timestamps = sorted(timestamps, reverse=True)
The sorted_timestamps variable will now contain a new list with the timestamps sorted in descending order.
If you want to sort the list in-place, you can use the following code:
timestamps.sort(reverse=True)
The timestamps list will now be sorted in descending order.
The above is the detailed content of How to Sort a List of Timestamps in Descending Order in Python?. For more information, please follow other related articles on the PHP Chinese website!