Python List sort() Method

Filed Under: Python
Python Sort List

Python List sort() method sorts the list elements in the natural ordering. The sorting happens in-place, so the list is modified.

Python has a built-in function – sorted() – which is used to create a sorted list from an iterable.

1. Python Sort List in Natural Order

When we sort a list of numbers, the natural ordering is to sort them in the increasing order.


numbers_list = [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]

print(f'Before sorting: {numbers_list}')

numbers_list.sort()

print(f'After sorting: {numbers_list}')

Output:


Before sorting: [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]
After sorting: [1.0, 2.2, 3.4, 3.8, 4.1, 5.1]
Recommended Read: Python f-strings

The default sorting is implemented for strings also. Here is a simple example to sort a list of strings.


str_list = ['a', 'c', 'd', 'b', 'B', 'C', '1']
str_list.sort()
print(str_list)  # ['1', 'B', 'C', 'a', 'b', 'c', 'd']

2. Sorting a List in Reverse Order

If you want the sorting to be done in the reversed order, pass the reverse argument as True. We can use this to sort a list of numbers in the descending order.


numbers_list = [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]

print(f'Before sorting: {numbers_list}')

numbers_list.sort(reverse=True)

print(f'After sorting: {numbers_list}')

Output:


Before sorting: [3.4, 5.1, 2.2, 4.1, 1.0, 3.8]
After sorting: [5.1, 4.1, 3.8, 3.4, 2.2, 1.0]

3. Sorting a Nested List

If we call the sort() function on a nested list, only the first elements from the list elements are used for the sorting. Let’s understand this with a simple example.


numbers = [[1, 2], [2, 1], [4, 3], [5, 2], [3, 3]]

print(f'Before sorting: {numbers}')

numbers.sort()

print(f'After sorting: {numbers}')

Output:


Before sorting: [[1, 2], [2, 1], [4, 3], [5, 2], [3, 3]]
After sorting: [[1, 2], [2, 1], [3, 3], [4, 3], [5, 2]]

It’s clear that the sorting is performed based on the first element in the nested list.

But, sometimes we want to sort the nested list based on different elements position.

Let’s say the nested list contains information about a Persons’ name, age, and gender. Let’s see how to sort this nested list based on the age, which is the second element in the nested list.


def custom_key(people):
    return people[1]  # second parameter denotes the age


persons = [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alexa', 22, 'F']]

print(f'Before sorting: {persons}')

persons.sort(key=custom_key)

print(f'After sorting: {persons}')

Output:


Before sorting: [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alexa', 22, 'F']]
After sorting: [['Alexa', 22, 'F'], ['Trudy', 25, 'M'], ['Bob', 25, 'M'], ['Alice', 26, 'F']]

We are using the key argument to specify the element to be used for the sorting purpose. The custom_key function returns the key to sort the list.

4. Custom Logic to Sort a List

We can also implement your own logic to sort the list elements.

In the last example, we used the age as the key element to sort our list.

But there goes a saying, “Ladies first!”.

So, we want to sort our list in such a way that the female gender gets priority over the male. If the gender of two persons matches, the younger one gets a higher priority.

So, we have to use the key argument in our sort function. But the compare function needs to be converted into a key.

So, we need to import a library called functools. We will use the function cmp_to_key() to convert our compare function into a key.


import functools


def compare_function(person_a, person_b):
    if person_a[2] == person_b[2]:  # if their gender become same
        return person_a[1] - person_b[1]  # return True if person_a is younger
    else:  # if their gender not matched
        if person_b[2] == 'F':  # give person_b first priority if she is female
            return 1
        else:  # otherwise give person_a first priority
            return -1


persons = [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 24, 'M'], ['Alexa', 22, 'F']]

print(f'Before sorting: {persons}')

persons.sort(key=functools.cmp_to_key(compare_function))

print(f'After sorting: {persons}')

Output:


Before sorting: [['Alice', 26, 'F'], ['Trudy', 25, 'M'], ['Bob', 24, 'M'], ['Alexa', 22, 'F']]
After sorting: [['Alexa', 22, 'F'], ['Alice', 26, 'F'], ['Bob', 24, 'M'], ['Trudy', 25, 'M']]

The list is sorted based on the gender first. Then it’s sorted based on the age of the persons.

5. Sorting a List of Objects

The default sorting works on numbers and strings. But, it won’t work on the list of custom objects.

Let’s see what happens when we try to run the default sorting on a list of objects.


class Employee:

    def __init__(self, n, a, gen):
        self.name = n
        self.age = a
        self.gender = gen

    def __str__(self):
        return f'Emp[{self.name}:{self.age}:{self.gender}]'

    # List uses __repr__, so overriding it to print useful information
    __repr__ = __str__


e1 = Employee('Alice', 26, 'F')
e2 = Employee('Trudy', 25, 'M')
e3 = Employee('Bob', 24, 'M')
e4 = Employee('Alexa', 22, 'F')

emp_list = [e1, e2, e3, e4]

print(f'Before Sorting: {emp_list}')

try:
    emp_list.sort()
except TypeError as te:
    print(te)

Output:


Before Sorting: [Emp[Alice:26:F], Emp[Trudy:25:M], Emp[Bob:24:M], Emp[Alexa:22:F]]
'<' not supported between instances of 'Employee' and 'Employee'

In this case, we have to mandatorily provide the key function to specify the objects’ field to be used for sorting.


# sorting based on age
def sort_by_age(emp):
    return emp.age


emp_list.sort(key=sort_by_age)
print(f'After Sorting By Age: {emp_list}')

Output:


After Sorting By Age: [Emp[Alexa:22:F], Emp[Bob:24:M], Emp[Trudy:25:M], Emp[Alice:26:F]]

We can also utilize the functools module to create custom sorting logic for the list elements.

References: Official API Documentation

Comments

  1. DEANMAUER says:

    Thanks for sharing. More helpful for completing assignment and gained more stuffs. Thank you

Leave a Reply

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

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages