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 – list.sort()
The syntax of sort() method is:
mylist.sort(cmp=None, key=None, reverse=False)
- cmp specifies a custom comparison function of two arguments (iterable elements) which should return a negative, zero or positive number depending on whether the first argument is considered smaller than, equal to, or larger than the second argument. Example:
cmp=lambda x,y: cmp(x.lower(), y.lower())
- 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 is
None(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.
Example 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.
mylist = [21, 5, 8, 52, 21, 87, 52] mylist.sort() print(mylist)
[5, 8, 21, 21, 52, 52, 87]
The default behavior of sort() function is to arrange the items in ascending order.
Example 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.
mylist = [21, 5, 8, 52, 21, 87, 52] mylist.sort(reverse=True) print(mylist)
[87, 52, 52, 21, 21, 8, 5]
In this tutorial of Python Examples, we learned how to sort a Python list, with the help of well detailed example programs.
- Python Program to Find Unique Items of a List
- Python – Count the items with a specific value in the List
- Python List of Lists
- Shuffle Python List
- Python Program to Find Smallest Number in List
- Python – Check if Element is in List
- How to Reverse Python List?
- Python List without Last Element
- Python – List of Strings
- Python – Get Index or Position of Item in List