How to sort a list of tuples by the element at a given index with Python?

Sometimes, we want to sort a list of tuples by the element at a given index with Python.

In this article, we’ll look at how to sort a list of tuples by the element at a given index with Python.

How to sort a list of tuples by the element at a given index with Python?

To sort a list of tuples by the element at a given index with Python, we can use the sorted function with a lambda function that specifies which item in the tuple we want to sort the list of tuples by.

For instance, we write:

data = [(1, 2, 3), (1, 2, 1), (1, 1, 4)]
sorted_data = sorted(data, key=lambda tup: (tup[1], tup[2]))
print(sorted_data)

to call sorted to sort data by the value of the 2nd and 3rd items in each tuple in this order.

We specify this with a lambda function that returns a tuple with the 2nd and 3rd item in each tuple.

Therefore, data is [(1, 1, 4), (1, 2, 1), (1, 2, 3)].

Conclusion

To sort a list of tuples by the element at a given index with Python, we can use the sorted function with a lambda function that specifies which item in the tuple we want to sort the list of tuples by.