Sorting by arbitrary lambda

This is such a common need that support for it has been added to the standard library, in the form of operator.itemgetter:

from operator import itemgetter
mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
mylist.sort(key=itemgetter(1)) # or sorted(mylist, key=...)

The answer is to use "sorted", i.e.

sorted(mylist, key=lambda x: x[1])

You basically have it already:

>>> mylist = [["quux", 1, "a"], ["bar", 0, "b"]]
>>> mylist.sort(key=lambda x: x[1])
>>> print mylist

gives:

[['bar', 0, 'b'], ['quux', 1, 'a']]

That will sort mylist in place.

[this para edited thanks to @Daniel's correction.] sorted will return a new list that is sorted rather than actually changing the input, as described in http://wiki.python.org/moin/HowTo/Sorting/.


You have two options, very close to what you described, actually:

mylist.sort(key=lambda x: x[1]) # In place sort
new_list = sorted(mylist, key=lambda x: x[1])

Tags:

Python

Sorting