Python List - Sorting - list.sort()
Python - Sort List
To sort a python list in ascending or descending order, you can use sort() method of List class.
In this tutorial, we shall use sort() function and sort the given list in ascending or descending order.
Syntax of list.sort()
The syntax of sort() method is:
mylist.sort(*, key=None, reverse=False)
where
- key specifies a function of one argument that is used to extract a comparison key from each list element:
key=str.lower
. The default value isNone
(compare the elements directly). - reverse is a boolean value. If set to True, then the list elements are sorted as if each comparison were reversed.
Examples
1. Sort a list in ascending order
To sort a list in ascending order, you just have to call sort() method on the list without any arguments. In the following example, we have a list of numbers. We will arrange the items of this list in ascending order.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort()
print(mylist)
Output
[5, 8, 21, 21, 52, 52, 87]
The default behavior of sort() function is to arrange the items in ascending order.
2. Sort a list in descending order
To sort a list in descending order, you can to pass reverse=True argument to the sort() function.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort(reverse=True)
print(mylist)
Output
[87, 52, 52, 21, 21, 8, 5]
Summary
In this tutorial of Python Examples, we learned how to sort a Python list, with the help of well detailed example programs.