It's the first time I am looking at Python and confused with the following lambda expression:
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=lambda pair: pair[1])
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]
I am not able to understand how it is 4, 1, 3, and 2?
sort function accepts returning value of a lambda as the key parameter to sort the list using it. So what's happening here is that the lambda function iterates over the list and passes pair[1] of each member of the list which is the textual representation of the number and because these values are a string, the sort function sorts them in alphabetical order. First (f)our, then (o)ne and so on.
Mark
For some things it's trivial to sort them, like real numbers, and English words.
Other things are harder to sort, like complex numbers, Chinese words, cars...
Or there may be multiple ways. I.e. people can be sorted by name, age, height...
That's why the sort function let's you choose what to sort by. You can pass a small function that converts the object (i.e. person) to the thing to sort (i.e. age).
The syntax
lambda pair: pair[1]means
def f(pair): return pair[1]