Categories
Python Answers

How to sort list in descending order with Python?

Spread the love

Sometimes, we want to sort list in descending order with Python.

In this article, we’ll look at how to sort list in descending order with Python.

How to sort list in descending order with Python?

To sort list in descending order with Python, we can use the sorted function with the reverse parameter set to True.

For instance, we write:

timestamps = [
    "2020-04-20 10:07:30", "2020-04-20 10:07:38", "2020-04-20 10:07:52",
    "2020-04-20 10:08:22", "2020-04-20 10:08:22", "2020-04-20 10:09:46",
    "2020-04-20 10:10:37", "2020-04-20 10:10:58", "2020-04-20 10:11:50",
    "2020-04-20 10:12:13", "2020-04-20 10:12:13", "2020-04-20 10:25:38"
]
s = sorted(timestamps, reverse=True)
print(s)

We call sorted with the timestamps list and reverse set to True to sort timestamps in reverse order and return the sorted list.

Therefore, s is:

['2020-04-20 10:25:38', '2020-04-20 10:12:13', '2020-04-20 10:12:13', '2020-04-20 10:11:50', '2020-04-20 10:10:58', '2020-04-20 10:10:37', '2020-04-20 10:09:46', '2020-04-20 10:08:22', '2020-04-20 10:08:22', '2020-04-20 10:07:52', '2020-04-20 10:07:38', '2020-04-20 10:07:30']

Conclusion

To sort list in descending order with Python, we can use the sorted function with the reverse parameter set to True.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *