The Python Oracle

Sort a list of tuples by 2nd item (integer value)

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Dreamlands

--

Chapters
00:00 Sort A List Of Tuples By 2nd Item (Integer Value)
00:20 Answer 1 Score 236
00:51 Accepted Answer Score 858
01:25 Answer 3 Score 45
01:44 Answer 4 Score 51
01:57 Thank you

--

Full question
https://stackoverflow.com/questions/1069...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #list #tuples

#avk47



ACCEPTED ANSWER

Score 858


Try using the key keyword argument of sorted(), which sorts in increasing order by default:

sorted(
    [('abc', 121), ('abc', 231), ('abc', 148), ('abc', 221)], 
    key=lambda x: x[1]
)

key should be a function that identifies how to retrieve the comparable element from your data structure. In your case, it is the second element of the tuple, so we access [1].

For optimization, see jamylak's response using operator.itemgetter(1), which is essentially a faster version of lambda x: x[1].




ANSWER 2

Score 236


>>> from operator import itemgetter
>>> data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]
>>> sorted(data,key=itemgetter(1))
[('abc', 121), ('abc', 148), ('abc', 221), ('abc', 231)]

IMO using itemgetter is more readable in this case than the solution by @cheeken. It is also faster since almost all of the computation will be done on the c side (no pun intended) rather than through the use of lambda.

>python -m timeit -s "from operator import itemgetter; data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=itemgetter(1))"
1000000 loops, best of 3: 1.22 usec per loop

>python -m timeit -s "data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]" "sorted(data,key=lambda x: x[1])"
1000000 loops, best of 3: 1.4 usec per loop



ANSWER 3

Score 51


Adding to Cheeken's answer, This is how you sort a list of tuples by the 2nd item in descending order.

sorted([('abc', 121),('abc', 231),('abc', 148), ('abc',221)],key=lambda x: x[1], reverse=True)



ANSWER 4

Score 45


As a python neophyte, I just wanted to mention that if the data did actually look like this:

data = [('abc', 121),('abc', 231),('abc', 148), ('abc',221)]

then sorted() would automatically sort by the second element in the tuple, as the first elements are all identical.