How does Python sort a list of tuples?

Yes, this is the default. In fact, this is the basis of the classic "DSU" (Decorate-Sort-Undecorate) idiom in Python. See Code Like a Pythonista.


It automatically sorts a list of tuples by the first elements in the tuples, then by the second elements and so on tuple([1,2,3]) will go before tuple([1,2,4]). If you want to override this behaviour pass a callable as the second argument to the sort method. This callable should return 1, -1, 0.


No, tuples are sequence types just like strings. They are sorted the same, by comparing each element in turn:

>>> import random
>>> sorted([(0,0,0,int(random.getrandbits(4))) for x in xrange(10)])
[(0, 0, 0, 0), (0, 0, 0, 4), (0, 0, 0, 5), (0, 0, 0, 7), (0, 0, 0, 8),
(0, 0, 0, 9), (0, 0, 0, 12), (0, 0, 0, 12), (0, 0, 0, 12), (0, 0, 0, 14)]

The three zeroes are only there to show that something other than the first element must be getting inspected.

Tags:

Python