How does Python sort a list of tuples?

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

+52
python
Mar 13 '09 at 19:09
source share
5 answers

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

+66
Mar 13 '09 at 19:13
source share

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

+8
Mar 13 '09 at 19:12
source share

No, tuples are sequence types just like strings. They are sorted the same way, comparing each item 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)] 

Three zeros are only there to show that something other than the first element needs to be checked.

+5
Mar 13 '09 at 19:13
source share

Try using the internal list sorting method and pass in lambda. If the first element of the tuples is an integer, this should work.

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

You can use any called for comparison function, not necessarily lambda. However, it needs to return -1 (less), 0 (equal) or 1 (more).

0
Mar 13 '09 at 19:14
source share

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

0
Mar 13 '09 at 20:44
source share



All Articles