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 Largest Number in a List
- How to Insert Item at Specific Index in Python List?
- How to Append List to Another List in Python? – list.extend(list)
- Python List without Last Element
- Python – Convert List to Dictionary
- Python Program to Find Duplicate Items of a List
- How to Check if Python List is Empty?
- Python List – Add Item
- Python List of Dictionaries
- Python Program to Find Unique Items of a List