Fix Python – Sort tuples based on second parameter

Question

Asked By – user974703

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

("Person 1",10)
("Person 2",8)
("Person 3",12)
("Person 4",20)

What I want produced, is the list sorted in ascending order, by the second value of the tuple. So L[0] should be ("Person 2", 8) after sorting.

How can I do this? Using Python 3.2.2 If that helps.

Now we will see solution for issue: Sort tuples based on second parameter


Answer

You can use the key parameter to list.sort():

my_list.sort(key=lambda x: x[1])

or, slightly faster,

my_list.sort(key=operator.itemgetter(1))

(As with any module, you’ll need to import operator to be able to use it.)

This question is answered By – Sven Marnach

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