4

Let's say I have the following list.

foo = [["A", 1], ["B", 2], ["C", 1]]

I want to sort by the second element in the list, so I run the following.

foo.sort(key=lambda i: i[1])

Now, foo has the following order.

[['A', 1], ['C', 1], ['B', 2]]

Is there a good way to sort by the first element in the event that the second element in the list is equal? Say the order I want is the following.

[['C', 1], ['A', 1], ['B', 2]]
Ayrx
  • 2,092
  • 5
  • 26
  • 34
  • http://stackoverflow.com/questions/16193578/how-do-i-perform-secondary-sorting-in-python – shaktimaan Aug 26 '14 at 02:40
  • 1
    Is this a homework assignment of sorts? [You are the second one to ask this question in about an hour](http://stackoverflow.com/q/25496595/198633) – inspectorG4dget Aug 26 '14 at 02:52
  • @inspectorG4dget Nope, legitimate problem I am facing. Not really the same question anyway, I'm asking how to sort a list in the event that the first index is equal. – Ayrx Aug 26 '14 at 02:54

2 Answers2

5

Just set your key to a tuple of the last, then first element. Tuples are automatically sorted in the way you describe (sorting on first element first, then second, and so on).

foo.sort(key=lambda i: (i[1], i[0]))

Note that if you don't absolutely need your original lists to be in the given order, you could sort the original list directly if you could switch the order. If you make your list foo = [[1, "A"], [2, "B"], [1, "C"]] then you could just do foo.sort() and that's it. You could convert your list into that format by doing foo = [reversed(i) for i in foo].

BrenBarn
  • 242,874
  • 37
  • 412
  • 384
  • Ah interesting! I didn't realize this is possible. Will be accepting this answer shortly. :) – Ayrx Aug 26 '14 at 02:49
2

Just add the second index to the sort function:

foo.sort(key=lambda i: (i[1], i[0]))
fabrizioM
  • 46,639
  • 15
  • 102
  • 119
  • 1
    Thanks for the answer! But it looks like Bren answered first so I'll be accepting his. Upvoted anyway. :) – Ayrx Aug 26 '14 at 02:50