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

How do I sort a Python list in descending order?

Patricia Arquette
Release: 2024-11-27 00:52:10
Original
447 people have browsed it

How do I sort a Python list in descending order?

Python List Sort in Descending Order

Sorting a list in descending order becomes necessary when you need to prioritize elements based on their magnitude. To achieve this in Python, we delve into the details of the built-in sorting function.

How to Sort a List in Descending Order

Python provides a straightforward way to sort a list in descending order using the sorted() function:

sorted_timestamps = sorted(timestamps, reverse=True)
Copy after login

The reverse argument, set to True, reverses the sorting order, effectively sorting the list in descending order.

Alternatively, you can modify the original list in-place with the sort() method:

timestamps.sort(reverse=True)
Copy after login

Example

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"
]
Copy after login

The sorted version of this list in descending order is:

["2010-04-20 10:25:38", "2010-04-20 10:12:13", "2010-04-20 10:12:13", "2010-04-20 10:11:50", "2010-04-20 10:10:58", "2010-04-20 10:10:37", "2010-04-20 10:09:46", "2010-04-20 10:08:22", "2010-04-20 10:08:22", "2010-04-20 10:07:52", "2010-04-20 10:07:38", "2010-04-20 10:07:30"]
Copy after login

Documentation

For further insights, refer to the official Python documentation on sorting:

  • [Sorting HOW TO](https://docs.python.org/3/howto/sorting.html)

The above is the detailed content of How do I 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