Home >Backend Development >Python Tutorial >How do you sort a Python list in descending order?

How do you sort a Python list in descending order?

Linda Hamilton
Linda HamiltonOriginal
2024-11-16 10:06:02609browse

How do you sort a Python list in descending order?

Descending Order Sorting in Python Lists

Within a Python list, data can be arranged in either ascending or descending order based on specific criteria. You may encounter situations where you need your list sorted in descending sequence, with the highest values at the beginning.

Sorting a List in Descending Order

To sort a list in descending order, Python provides a simple method:

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"]
sorted_timestamps = sorted(timestamps, reverse=True)

The sorted() function returns a new sorted list with the original list remaining unchanged. By setting the reverse parameter to True, the function reverses the order, placing the highest values first. The resulting sorted_timestamps will be sorted in descending order.

Sorting a List In-Place

If you prefer to modify the original list directly instead of creating a new one, you can use the sort() method:

timestamps.sort(reverse=True)

The sort() method modifies the list in-place, sorting its elements in descending order.

Note:

The default sorting behavior is based on string comparison, which may not be appropriate for all data types. For custom sorting criteria, you can provide a comparison function as the second argument to the sorted() or sort() methods.

The above is the detailed content of How do you sort a Python list in descending order?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn