Fix Python – Sort a list of tuples by 2nd item (integer value) [duplicate]

Question

Asked By – Amyth

I have a list of tuples that looks something like this:

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

I want to sort this list in ascending order by the integer value inside the tuples. Is it possible?

Now we will see solution for issue: Sort a list of tuples by 2nd item (integer value) [duplicate]


Answer

Try using the key keyword with sorted().

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 itemgetter(1), which is essentially a faster version of lambda x: x[1].

This question is answered By – cheeken

This answer is collected from stackoverflow and reviewed by FixPython community admins, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0