Sort tuples based on second parameter
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.)
You may also apply the sorted
function on your list, which returns a new sorted list. This is just an addition to the answer that Sven Marnach has given above.
# using *sort method*
mylist.sort(key=lambda x: x[1])
# using *sorted function*
l = sorted(mylist, key=lambda x: x[1])