+2 votes
in Programming Languages by (73.8k points)
I have a list of tuples. When I sort it, it is sorted by the first item of the tuple. How can I sort the list by the second item of the tuples?

E.g.

Input list = [('c', 23), ('a', 55), ('e', 11), ('b', 45), ('d', 34), ('f', 5)]

Output list = [('f', 5), ('e', 11), ('c', 23), ('d', 34), ('b', 45), ('a', 55)]

1 Answer

+1 vote
by (348k points)
selected by
 
Best answer

There are many ways to sort a list of tuples by the second item of the tuples. Here are some pythonic ways:

Method 1:

>>> from operator import itemgetter
>>> aa=[('c',23),('a',55),('e',11),('b',45),('d',34),('f',5)]
>>> sorted(aa,key=itemgetter(1))
[('f', 5), ('e', 11), ('c', 23), ('d', 34), ('b', 45), ('a', 55)]

Method 2:

>>> aa
[('c', 23), ('a', 55), ('e', 11), ('b', 45), ('d', 34), ('f', 5)]
>>> sorted(aa,key=lambda x:x[1])
[('f', 5), ('e', 11), ('c', 23), ('d', 34), ('b', 45), ('a', 55)]

Method 3:

>>> aa
[('c', 23), ('a', 55), ('e', 11), ('b', 45), ('d', 34), ('f', 5)]
>>> aa.sort(key=lambda x:x[1])
>>> aa
[('f', 5), ('e', 11), ('c', 23), ('d', 34), ('b', 45), ('a', 55)]
 


...