Summary: In this tutorial, we will see how to use the list.sort() to sort a list containing different objects such as numbers, strings, dictionaries, etc in Python.

The list.sort() method in Python sorts a given list in the order specified (by default it sorts in ascending order).

>>> l = [7, 2, 5, 1, 3, 9]
>>> l.sort()
>>> print(l)
[1, 2, 3, 5, 7, 9]

It does not return any data but modifies the list in place (without using any extra list).

Parameters

The list.sort() method accepts two parameters that are optional:

ParameterDescription
reverse (optional)Boolean to sort the list in reverse (descending) order.
Its default value is False, so Python by default sorts the list in ascending order.
key (optional)Function to determine the criteria for sorting.

The reverse parameter is useful when we need to sort the elements of the list in descending order.

>>> l = [7, 2, 5, 1, 3, 9]
>>> l.sort(reverse=True)
>>> print(l)
[9, 7, 5, 3, 2, 1]

The second parameter i.e. the key decides the criteria of sorting. This is useful when we want to define a way of comparing different than the default way.

It accepts a function that should return a value. The list.sort() method uses this value to decide the order of the elements.

For example, in the following code, we are instructing the sort() method to sort the elements according to the length of the elements through the key parameter:

>>> l = ["tom", "jerry", "noddy", "oggy", "bob"]
>>> def func(e):
...     return len(e)
... 
>>> l.sort(key=func)
>>> print(l)
['tom', 'bob', 'oggy', 'jerry', 'noddy']

We can also write the above code as follows:

>>> l = ["tom", "jerry", "noddy", "oggy", "bob"]
>>> l.sort(key=len)
>>> print(l)
['tom', 'bob', 'oggy', 'jerry', 'noddy']

Here, we are explicitly instructing Python to consider the integer value returned by the len() (for each element) for the comparision.

Let’s see some more examples using the Python list.sort() method for better understanding.

Examples using list.sort()

Example 1: Sort list of strings using list.sort() in Python

>>> l = ["Python", "Java", "C++"]
>>> l.sort()
>>> print(l)
['C++', 'Java', 'Python']

Example 4: Sort list of numbers in descending order using the list.sort() function.

>>> l = [5, 1, 10, 6, 3]
>>> l.sort(reverse=True)
>>> print(l)
[10, 6, 5, 3, 1]

Example 3: Sort list of dictionaries based on a certain key’s value using the list.sort() method.

>>> l = [{'name': 'Jon', 'roll_no': 15}, {'name': 'Jackie', 'roll_no': 8}, {'name': 'AK', 'roll_no': 32}]
>>> def func(e):
...     return e['roll_no']
... 
>>> l.sort(key=func)
>>> print(l)
[{'name': 'Jackie', 'roll_no': 8}, {'name': 'Jon', 'roll_no': 15}, {'name': 'AK', 'roll_no': 32}]

If we want to write this code using the lambda function, it would be as follows:

>>> l = [{'name': 'Jon', 'roll_no': 15}, {'name': 'Jackie', 'roll_no': 8}, {'name': 'AK', 'roll_no': 32}]
>>> l.sort(key=lambda e: e['roll_no'])
>>> print(l)
[{'name': 'Jackie', 'roll_no': 8}, {'name': 'Jon', 'roll_no': 15}, {'name': 'AK', 'roll_no': 32}]

Example 4: Sort list of user-defined objects using the sort() method.

>>> class Student:
...     def __init__(self, name, marks):
...         self.name = name
...         self.marks = marks
...         
...    def __repr__(self):
...         return self.name
...        
>>> l = [Student('Andrew', 85), Student('Roman', 62), Student('Ak', 76)]
>>> l.sort(reverse=True, key=lambda e: e.marks)
>>> print(l)
[Andrew, Ak, Roman]

Here, we have sorted the list of objects of the Student class on the basis of marks in descending order.

Conclusion

The list.sort() method in Python sorts the elements of the given list in ascending order (by default).

If we pass reverse=True as parameter, it sorts the list in descending order.

The key parameter of the sort method is used to define the base of comparison for the elements of the list.

Leave a Reply