✉️
Questions?
Email me

How to Sort a List of Tuples Based on Multiple Elements

Published Dec 5, 2020  ∙  Updated Jan 3, 2022

Suppose we have a list of tuples that we want to sort with multiple conditions.

lst_of_tuples = [(4, 5), (2, 15), (3, 10), (1, 5)]

Suppose we want to sort based on the second element in the tuple, then the first. This means that when the second element in the tuple is the same, we want to resort to comparing the first element.

In the scenario above, we would first sort by the second element: 5, 5, 10, 15.

We have two 5s, so we will then sort those two tuples by the first element: 1, 4.

sorted_lst_of_tuples = [(1, 5), (4, 5), (3, 10), (2, 15)]

To do this, we can use the key parameter in sorted(). We can specify the priority of the sorting element by returning a tuple containing the sort order.

sorted_lst_of_tuples = sorted(lst_of_tuples, key=lambda x: (x, x))

x represents each list element. In our case, a single tuple.

x represents the second element in the tuple while x represents the first element.