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.
Frequently Asked:
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.
Latest Python - Video Tutorial
Summary
We learned about two different ways to sort a List in descending order in Python. Thanks.
Latest Video Tutorials