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?

2

1 Answer

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

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

2