How does Python sort a list of tuples?

Python

Python Problem Overview


Empirically, it seems that Python's default list sorter, when passed a list of tuples, will sort by the first element in each tuple. Is that correct? If not, what's the right way to sort a list of tuples by their first elements?

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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.

Solution 3 - Python

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.

Solution 4 - Python

Try using the internal list sort method and pass a lambda. If your tuples first element is a integer, this should work.

# l is the list of tuples
l.sort(lambda x,y: x-y)

You can use any callable for the compare function, not necessarily a lambda. However it needs to return -1 (less than), 0 (equal) or 1 (greater than).

Solution 5 - Python

Check out "Devin Jeanpierre" answer to this question sort-a-dictionary-in-python-by-the-value where he says to use a tuple and shows how to sort by the second value

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionmikeView Question on Stackoverflow
Solution 1 - PythonVasilView Answer on Stackoverflow
Solution 2 - PythonzweiterlindeView Answer on Stackoverflow
Solution 3 - PythonunwindView Answer on Stackoverflow
Solution 4 - Pythonm-sharpView Answer on Stackoverflow
Solution 5 - PythonGern BlanstonView Answer on Stackoverflow