how to sort a lsit of tuple of tuples in python

You can sort a list of tuple of tuples in Python using the sorted() method along with a lambda function.

Here's an example:

main.py
my_list = [(1, 5, 2), (3, 2, 6), (3, 1, 1), (2, 2, 2)]
sorted_list = sorted(my_list, key=lambda x: (x[0], x[1], x[2]))

print(sorted_list)
139 chars
5 lines

Output: [(1, 5, 2), (2, 2, 2), (3, 1, 1), (3, 2, 6)]

The key parameter in the sorted() method takes a lambda function which specifies the criteria for the sorting. In this example, the lambda function returns a tuple of the elements in each tuple of tuples to be sorted by their index.

Therefore, the outer list of tuples is sorted first by the first element, then by the second element and finally by the third element.

related categories

gistlibby LogSnag