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
Release: 2024-11-23 12:15:16
Original
884 people have browsed it

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

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

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!

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