Contents
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)
where
- 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 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.
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.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort()
print(mylist)
Run Output
[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.
Python Program
mylist = [21, 5, 8, 52, 21, 87, 52]
mylist.sort(reverse=True)
print(mylist)
Run 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.
Related Tutorials
- How to Access List Items in Python?
- Python – Check if List Contains all Elements of Another List
- Shuffle Python List
- Python – Check if Element is in List
- Python Program to Find Unique Items of a List
- How to Reverse Python List?
- Python Program to Find Smallest Number in List
- Python – Convert List to Dictionary
- How to Check if Python List is Empty?
- Python – Get Index or Position of Item in List