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 list
  • sort is method name
  • key is a function that can take the element as argument, and return a value
  • reverse if True, sorts the list in descending order, or if False, sorts the list in ascending order
ADVERTISEMENT

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}')
Try Online

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}')
Try Online

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.