65

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)
]
4
  • 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). Commented Feb 21, 2012 at 19:58
  • 1
    stackoverflow.com/questions/4233476/…
    – cardamom
    Commented Mar 5, 2019 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). Commented Jan 15, 2023 at 6:59
  • - Oh, wait, never mind. @cardamom's duplicate link is better, and one I already had saved as a canonical. Commented Jan 15, 2023 at 7:00

1 Answer 1

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

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

2
  • 3
    May be sorted(unsorted, key=lambda element: (element[1:])) or sorted(unsorted, key=lambda element: (element[1:3])) is better
    – pod2metra
    Commented Feb 21, 2012 at 11:32
  • 9
    @pod2metra There are numerous possibilities. Probably best would be operator.itemgetter(1,2). Commented Feb 21, 2012 at 12:35

Not the answer you're looking for? Browse other questions tagged or ask your own question.