The Python Oracle

How to sort a list/tuple of lists/tuples by the element at a given index?

Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn

--

Music by Eric Matyas
https://www.soundimage.org
Track title: Puzzle Game 3 Looping

--

Chapters
00:00 Question
00:38 Accepted answer (Score 1458)
01:10 Answer 2 (Score 300)
01:20 Answer 3 (Score 87)
01:46 Answer 4 (Score 67)
02:09 Thank you

--

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

Accepted answer links:
[reverse=True]: https://docs.python.org/3/howto/sorting....

--

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

--

Tags
#python #list #sorting #tuples

#avk47



ACCEPTED ANSWER

Score 1521


sorted_by_second = sorted(data, key=lambda tup: tup[1])

or:

data.sort(key=lambda tup: tup[1])  # sorts in place

The default sort mode is ascending. To sort in descending order use the option reverse=True:

sorted_by_second = sorted(data, key=lambda tup: tup[1], reverse=True)

or:

data.sort(key=lambda tup: tup[1], reverse=True)  # sorts in place



ANSWER 2

Score 315


from operator import itemgetter
data.sort(key=itemgetter(1))



ANSWER 3

Score 67


I just want to add to Stephen's answer if you want to sort the array from high to low, another way other than in the comments above is just to add this to the line:

reverse = True

and the result will be as follows:

data.sort(key=lambda tup: tup[1], reverse=True)



ANSWER 4

Score 30


Stephen's answer is the one I'd use. For completeness, here's the DSU (decorate-sort-undecorate) pattern with list comprehensions:

decorated = [(tup[1], tup) for tup in data]
decorated.sort()
undecorated = [tup for second, tup in decorated]

Or, more tersely:

[b for a,b in sorted((tup[1], tup) for tup in data)]

As noted in the Python Sorting HowTo, this has been unnecessary since Python 2.4, when key functions became available.