Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sorting by arbitrary lambda

Tags:

python

sorting

People also ask

What is lambda in sorting?

When we sort a list with a lambda function, it enables the creation of custom sorting orders. The sort() method and sorted() function can sort lists in descending or ascending (alphabetical and numerical) order by default.

How do you sort using key lambda?

To define lambda, you specify the object property you want to sort and python's built-in sorted function will automatically take care of it. If you want to sort by multiple properties then assign key = lambda x: (property1, property2). To specify order-by, pass reverse= true as the third argument(Optional.

What is the difference between using sorted NUMS and NUMS sort ()?

The primary difference between the two is that list. sort() will sort the list in-place, mutating its indexes and returning None , whereas sorted() will return a new sorted list leaving the original list unchanged.

What is the use of key lambda in Python?

In Python, lambda is a keyword used to define anonymous functions(functions with no name) and that's why they are known as lambda functions. Basically it is used for defining anonymous functions that can/can't take argument(s) and returns value of data/expression.


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])

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])