About Python List Sorting
In Python, list maintains the order of the elements as they are inserted or created.
So, list elements can be sorted in descending or ascending order.
Sorting Python list elements in descending order
Using sort(reverse=True) Method:
1. Create a list of string with fruit names (fruit_list = ["Banana", "Apple", "Orange", "Cherry"]
) where fruit_list
is the list variable and ["Banana", "Apple", "Orange", "Cherry"]
is the list with elements. The list elements are not in descending order.
2. To sort the elements of the above list, you can use fruit_list.sort(reverse=True)
where sort(reverse=True)
method is used to sort the list elements in descending order. If you now print the fruit_list, the list elements will be printed in descending order.
Please note that 'reverse=True' has been passed to the sort() method as argument to sort the list elements in descending order.
In the second example, a list of integer numbers has been sorted in descending order.
Please take a closer look at the following examples:
Example of sorting list elements using sort(reverse=True) method
Output of the above example
Sorted list of string elements: ['Orange', 'Cherry', 'Banana', 'Apple'] Sorted list of integer elements: [5, 4, 3, 2, 1]
Using sorted(list, reverse=True) function:
1. Create a list of string with fruit names fruit_list = ["Banana", "Apple", "Orange", "Cherry"]
where fruit_list
is the list variable and ["Banana", "Apple", "Orange", "Cherry"]
is the list with elements. The list elements are not in descending order.
2. Use sorted_list = sorted(fruit_list, reverse=True)
where sorted_list
is a variable and sorted(fruit_list, reverse=True)
is the sorted() function with list argument. If you now print the sorted_list, the list elements will be printed in descending order.
Please note that 'fruit_list' and 'reverse=True' have been passed to the sorted() function as arguments to sort the list elements in descending order.
In the second example, a list of integer numbers has been sorted in descending order.
Please take a closer look at the following examples:
Example of sorting list elements using sorted(list, reverse=True) function
Output of the above example
Sorted list of string elements: ['Orange', 'Cherry', 'Banana', 'Apple'] Sorted list of integer elements: [5, 4, 3, 2, 1]