Sort List by Key in Python

When we sort a list it’s sort by values. If we have a list of tuples, it’s sort by the first element by default.

my_list = [(5, 7), (4, 3), (8, 6), (3, 5)]
my_list.sort()

print('Sorted list:', my_list)

This code will sort by the fist element of a tuple.

Sorted list: [(3, 5), (4, 3), (5, 7), (8, 6)]

Let’s that we want to use a key to sort a list by the second element.

# takes second element for sort
def secondElement(elem):
    return elem[1]

my_list = [(5, 7), (4, 3), (8, 6), (3, 5)]

# sorts with a key
my_list.sort(key=secondElement)

print('Sorted list:', my_list)

Now, as you can see the second element is used to sort a list. All values are sorted in the ascending order: 3, 5, 6, 7.

In a similar way, you can sort a list by the third element:

# takes second element for sort
def thirdElement(elem):
    return elem[2]

my_list = [(5, 7, 4), (4, 3, 8), (8, 6, 2), (3, 5, 1)]

# sorts with a key
my_list.sort(key=thirdElement)

print('Sorted list:', my_list)

This time the list is sorted by the first element of the tuple elem[2].

Sorted list: [(3, 5, 1), (8, 6, 2), (5, 7, 4), (4, 3, 8)]