'Sort a list of tuples depending on two elements [duplicate]

Possible Duplicate:
python: how to sort a complex list on two different keys

I've got a list of tuples. I want to sort them depending two elements. Here is following example

unsorted = [('a', 4, 2), ('a', 4, 3), ('a', 7, 2), ('a', 7, 3), ('b', 4, 2), ('b', 4, 3), ('b', 7, 2), ('b', 7, 3)]
sorted   = [('a', 4, 2), ('b', 4, 2), ('a', 4, 3), ('b', 4, 3), ('a', 7, 2), ('b', 7, 2), ('a', 7, 3), ('b', 7, 3)]

I know how to sort them on the second element:

sorted(unsorted, key = lambda element : element[1])

But how to do that with two keys?



Solution 1:[1]

sorted(unsorted, key=lambda element: (element[1], element[2]))

I've assumed an order for the keys from the sample output.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Michael J. Barber