Sort a list of tuples depending on two elements

Question:

I have a list of tuples, like so:

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

I know that, for example to sort them by the second element, I can use:

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

But how can I sort the list depending on multiple keys?

The expected result should be like:

[
    ('a', 4, 2), ('b', 4, 2), ('a', 4, 3), ('b', 4, 3),
    ('a', 7, 2), ('b', 7, 2), ('a', 7, 3), ('b', 7, 3)
]
Asked By: Razer

||

Answers:

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

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

Answered By: Michael J. Barber
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.