Remember that a lambda is a function. What do you do with functions? You call them of course. So the
sort
method calls the function passed as
key
on each
pair
to decide what to sort by (the second element in
pair
,
pair[1]
).
Perhaps it's useful to consider the function
map
that takes a list of values and a function to apply to each value, producing a new list.
map
exists in the standard library, so I'm calling my implementation below
my_map
:
>>> def my_map(f, values):
... new_values = []
... for v in values:
... new_values.append(f(v))
... return new_values
...
>>> my_map(lambda v: v * 2, [1, 2, 3])
[2, 4, 6]
>>> my_map(lambda v: v.upper(), ["foo", "bar", "baz"])
['FOO', 'BAR', 'BAZ']
>>>
my_map
loops over each of the items in
values
, calling the function
f
on them (line 4) and putting those values in a new list which is returned. On line 7, I pass a lambda that just doubles its argument, so when
my_map
applies that to the items in
[1, 2, 3]
, you get the list
[2, 4, 6]
. It's a similar thing with the second example on line 9.