Home >Backend Development >Python Tutorial >How to Sort a List in Descending Order in Python?

How to Sort a List in Descending Order in Python?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-23 12:15:16895browse

How to Sort a List in Descending Order in Python?

Sorting List in Descending Order in Python

In Python, sorting a list in descending order can be achieved using the sorted() function or the sort() method.

# using sorted()
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)
print(sorted_timestamps)

This will create a new list with the elements sorted in descending order, leaving the original list unchanged.

To sort the list in-place, use the sort() method with reverse=True:

# using sort()
timestamps.sort(reverse=True)
print(timestamps)

For more details on sorting in Python, refer to the Sorting HOW TO documentation.

The above is the detailed content of How to Sort a List in Descending Order in Python?. 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