0

I want to sort by first element in tuple, and, if first element for some tuples is equal, by second element. For example, I have [(5,1),(1,2),(1,1),(4,3)] and I want to get [(1,1),(1,2),(4,3),(5,1)]

How can I do it in pythonic way?

Acapello
  • 127
  • 9
  • 1
    Possible duplicate of [How to sort (list/tuple) of lists/tuples?](http://stackoverflow.com/questions/3121979/how-to-sort-list-tuple-of-lists-tuples) – Florent Apr 28 '16 at 06:33

4 Answers4

2
d = [(5,1),(1,2),(1,1),(4,3)]
print(sorted(d,key=lambda x:(x[0],x[1])))

if you want better performance use itemgetter

backtrack
  • 7,996
  • 5
  • 52
  • 99
2
import operator
l = [(5,1),(1,2),(1,1),(4,3)]
print(sorted(l, key=operator.itemgetter(0,1))
Sven Hakvoort
  • 3,543
  • 2
  • 17
  • 34
0

You don't really need to specify the key since you want to sort on the list item itself.

>>> d = [(5,1),(1,2),(1,1),(4,3)]
>>> sorted(d)
[(1, 1), (1, 2), (4, 3), (5, 1)]
AKS
  • 18,983
  • 3
  • 43
  • 54
0

Remember, Sorted method will return a list object. In this case d still remains unsorted.

If you want to sort d you can use

>>>d.sort()

Hope it helps

Strik3r
  • 1,052
  • 8
  • 15