How to Sort a List of Tuples Based on Multiple Elements


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[1], x[0]))

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

x[1] represents the second element in the tuple while x[0] represents the first element.