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
Release: 2024-11-16 10:06:02
Original
607 people have browsed it

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)
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template