Sort a List in descending / reverse order in Python

In this article, we will discuss different ways to sort a list in descending order.

Table Of Contents

Sort a List in descending order in place

In Python, the list class provides a function sort(), which sorts the list in place. By default, it sorts the elements in list in ascending order. But if we provide value of reverse argument as True, then it sorts the elements in descending order. Let’s see an example,

listOfNumbers = [67, 78, 55, 44, 90, 98, 99, 76]

# Sort List in Descending Order in Place
listOfNumbers.sort(reverse=True)

print(listOfNumbers)

Output:

[99, 98, 90, 78, 76, 67, 55, 44]

Here, we sorted a list of numbers in descending order and in place.

Advertisements

Get a copy of sorted list (in descending order)

Python provides a function to sort any sequence,

newList = sorted(sequence, reverse)

It accepts a sequence and a boolean flag reverse as arguments, and returns a sorted copy of given sequence. By default, the value of reverse is False. Therefore, by default it sorts the copy of given sequence in ascending order. To sort the elements in descending order, pass the value of reverse argument as True. Let’s see an example,

listOfNumbers = [67, 78, 55, 44, 90, 98, 99, 76]

# Sort List in Descending Order
listOfNumbers = sorted(listOfNumbers, reverse=True)

print(listOfNumbers)

Output:

[99, 98, 90, 78, 76, 67, 55, 44]

Here, we got a sorted copy of given list. In which elements are sorted in descending order.

Summary

We learned about two different ways to sort a List in descending order in Python. Thanks.

Pandas Tutorials -Learn Data Analysis with Python

   

Are you looking to make a career in Data Science with Python?

Data Science is the future, and the future is here now. Data Scientists are now the most sought-after professionals today. To become a good Data Scientist or to make a career switch in Data Science one must possess the right skill set. We have curated a list of Best Professional Certificate in Data Science with Python. These courses will teach you the programming tools for Data Science like Pandas, NumPy, Matplotlib, Seaborn and how to use these libraries to implement Machine learning models.

Checkout the Detailed Review of Best Professional Certificate in Data Science with Python.

Remember, Data Science requires a lot of patience, persistence, and practice. So, start learning today.

Join a LinkedIn Community of Python Developers

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top