How to Sort a List in Python?

In this tutorial, you will learn how to sort a Python list in ascending and descending order.

Python List sort() method

With the help of the Python List sort() method, you can sort a Python list in ascending or descending order.

The list sort() method takes two parameters key and reverse, but these are optional parameters.

list.sort(key=..., reverse=...)

The list sort() method doesn’t return anything, it just updates the current list.

>>> a = [21, 32, 45, 14, 74]
>>> a.sort()
>>> print(a)
[14, 21, 32, 45, 74]
>>>

Python sort a list in Descending order

If you want to sort a Python list in descending order, you need to use the reverse parameter.

By default the reverse parameter is False, now you need to set it to True to sort a list in descending order.

>>> a = [21, 32, 45, 14, 74]
>>> a.sort(reverse=True)
>>> print(a)
[74, 45, 32, 21, 14]
>>>

Sort a list according to your own implementation

If you want to implement your own sorting logic, you need to use the key parameter. This key parameter takes a function, and you have to return the value based on which you want to sort.

In the following example, all programming languages are sorted according to their string length.

a = ['Java', 'Python', 'PHP', 'JavaScript', 'C++']

def myFunc(item):
    return len(item)

# Ascending order
a.sort(key=myFunc)

# For Descending order
# a.sort(key=myFunc, reverse=True)

print(a)
['PHP', 'C++', 'Java', 'Python', 'JavaScript']

Another Example:

Sorting a list of users by their age.

from pprint import pprint

a = [
    {'name':'Mark', 'age':45},
    {'name':'Alex', 'age':16},
    {'name':'Bob', 'age':32},
    {'name':'Tony', 'age':55},
]

def myFunc(item):
    return item['age']

# Ascending order
a.sort(key=myFunc)

# For Descending order
# a.sort(key=myFunc, reverse=True)

pprint(a)
[{'age': 16, 'name': 'Alex'},
 {'age': 32, 'name': 'Bob'},
 {'age': 45, 'name': 'Mark'},
 {'age': 55, 'name': 'Tony'}]

Leave a Reply

Your email address will not be published. Required fields are marked *