Python List – sort()
Python list.sort() method sorts the elements of the given list. We can sort the list in ascending or descending order by specifying reverse
parameter. We can also provide a function (where this function returns a value for each element) that can be used for comparison between the values of respective elements.
Syntax
The syntax to call sort() method on a list myList
is
myList.sort(*, key=None, reverse=False)
where
myList
is a Python listsort
is method namekey
is a function that can take the element as argument, and return a valuereverse
if True, sorts the list in descending order, or if False, sorts the list in ascending order
Examples
Sort a List in Ascending Order
In the following program, we initialize a list myList
with some integer values. We sort the elements in this list in ascending order, using sort()
method.
main.py
#take a list
myList = [4, 16, 2, 0, 5]
print(f'original list : {myList}')
#sorted list
myList.sort()
print(f'sorted list : {myList}')
Output
original list : [4, 16, 2, 0, 5]
sorted list : [0, 2, 4, 5, 16]
Sort a List in Descending Order
In the following program, we initialize a list myList
with some integer values. We sort the elements in this list in descending order, using sort()
method. For descending order, pass reverse=True
for sort()
method.
main.py
#take a list
myList = [4, 16, 2, 0, 5]
print(f'original list : {myList}')
#sorted list
myList.sort(reverse=True)
print(f'sorted list : {myList}')
Output
original list : [4, 16, 2, 0, 5]
sorted list : [16, 5, 4, 2, 0]
Conclusion
In this Python Tutorial, we learned how to sort the elements in a list in ascending or descending order using list.sort() method.