Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does Python sort a list of tuples?

Tags:

python

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?

like image 459
mike Avatar asked Mar 13 '09 19:03

mike


People also ask

How does sort work on tuples?

A tuple is a data type for immutable ordered sequences of elements. To sort elements of a tuple, we can use the sorted function, providing the tuple as the first argument. This function returns a sorted list from the given iterable, and we can easily convert this list into a tuple using the built-in function tuple.

Can you use sort on tuples in Python?

In Python, there are two ways, sort() and sorted() , to sort lists ( list ) in ascending or descending order. If you want to sort strings ( str ) or tuples ( tuple ), use sorted() .

How do you sort a list of tuples by second element in Python?

Use the key argument of the sorted() function to sort a list of tuples by the second element, e.g. sorted_list = sorted(list_of_tuples, key=lambda t: t[1]) . The function will return a new list, sorted by the second tuple element.

How do you sort a tuple in Python without sorting?

You can use one of the easiest sorting algorithm that is bubble sort. In case of tuples in tuple it will sort in order of first element of tuple. So ((32, "b"), (1, "c"), (23,"a")) Now if you sort it it will sort it in the order of 1st element of tuple.


2 Answers

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.

like image 143
Vasil Avatar answered Sep 19 '22 01:09

Vasil


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.

like image 27
unwind Avatar answered Sep 20 '22 01:09

unwind