Sort list in descending order Python
In this post, you will learn how to sort list in descending order using Python.
A list is an arranged collection of elements. It is used to store collections of data. It can contain a list of various types of data objects with a comma separated and enclosed within a square bracket. It is mutable, which means we can change the order of elements, individual elements can be replaced even after the list has been created. This is one of the leading reasons why lists are being used widely. Lists play an effective role in small projects as it consumes more memory.
Python list sort()
Python provides sort() method to sort the list in either ascending or descending order. By using this method, we can sort list of integers, floating point number, string and others.
Syntax of sort() method
list.sort(key=None, reverse=False)
Here, the key is optional parameter. It can be a function that extracts a comparison key from each list element. The reverse parameter is also optional, by default it is false. If true, the sorted list will be reversed.
Example1
The given example, sort the list of integers in descending order:
num = [11, 32, 12, 42, 41, 1, 39, 53]
num.sort(reverse=True)
print('List in Descending Order: ', num)
Output of the above code:
List in Descending Order: [53, 42, 41, 39, 32, 12, 11, 1]
Example2
The given example, sort the char list in descending order:
chr = ['e','a','w','l','c','d','n','m']
chr.sort(reverse=True)
print('List in Descending Order: ', chr)
Output of the above code:
List in Descending Order: ['w', 'n', 'm', 'l', 'e', 'd', 'c', 'a']
Example3
The given example, sort the string list in descending order:
fruits = ['apple','banana','pear','cherry','papaya','orange']
fruits.sort(reverse=True)
print('List in Descending Order:\n ', fruits)
Output of the above code:
List in Descending Order:
['pear', 'papaya', 'orange', 'cherry', 'banana', 'apple']
Related Articles
Convert dataframe column to listDataframe to list Python
Convert tuple to list Python
Convert list to set Python
Convert list to tuple Python
Convert list to set Python
Python convert list to numpy array
How to shuffle a list in Python
Print hollow diamond pattern in Python
Python *args **kwargs
Write a python program to sum all the numbers in a list
Shuffle list python
Convert array to list Python
Remove element from list Python
Convert list to dictionary Python
Python dict inside list
Convert list to string Python
Remove last element from list Python
Convert string to list Python
Python add list to list
Difference between tuple and list in Python
Python weather api
Alphabetical order Python
Python | Generate QR Code using pyqrcode module