61

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)
]
Karl Knechtel
  • 62,466
  • 11
  • 102
  • 153
Razer
  • 7,843
  • 16
  • 55
  • 103
  • 3
    The sorting done by Python is stable, meaning that you can in fact sort it twice, first on the least important element, then on the most important element. In certain cases this can in fact be faster (but only some times). – Lennart Regebro Feb 21 '12 at 19:58
  • 1
    https://stackoverflow.com/questions/4233476/sort-a-list-by-multiple-attributes – cardamom Mar 05 '19 at 15:26
  • I've reopened this, because the previous duplicate is focused on a slightly more complex case and a specific problem that comes up because of the extra complexity. Sorting by multiple keys in the same order, as here, is straightforward; sorting ascending by one key and descending by another is trickier, especially if either or both keys are strings (with integers, mathematical tricks are possible). – Karl Knechtel Jan 15 '23 at 06:59
  • - Oh, wait, never mind. @cardamom's duplicate link is better, and one I already had saved as a canonical. – Karl Knechtel Jan 15 '23 at 07:00

1 Answers1

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

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

Michael J. Barber
  • 24,518
  • 9
  • 68
  • 88