How to sort a list/tuple of lists/tuples by the element at a given index?
--------------------------------------------------
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow
--
Chapters
00:00 How To Sort A List/Tuple Of Lists/Tuples By The Element At A Given Index?
00:32 Accepted Answer Score 1521
00:55 Answer 2 Score 30
01:22 Answer 3 Score 315
01:28 Answer 4 Score 67
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/3121...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #sorting #tuples
#avk47
Hire the world's top talent on demand or became one of them at Toptal: https://topt.al/25cXVn
and get $2,000 discount on your first invoice
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Lost Meadow
--
Chapters
00:00 How To Sort A List/Tuple Of Lists/Tuples By The Element At A Given Index?
00:32 Accepted Answer Score 1521
00:55 Answer 2 Score 30
01:22 Answer 3 Score 315
01:28 Answer 4 Score 67
01:47 Thank you
--
Full question
https://stackoverflow.com/questions/3121...
--
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.