Sort List by Key in Python

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

This code will sort by the first 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.

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

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

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)]