Could you explain lambda function to me?

Chris Kaynor ckaynor at zindagigames.com
Tue Jun 2 14:33:53 EDT 2015


On Tue, Jun 2, 2015 at 11:14 AM, fl <rxjwg98 at gmail.com> wrote:

> Hi,
>
> I see the description of lambda at the online tutorial, but I cannot
> understand it. '42' is transferred to the function. What 'x' value should
> be? I do not see it says that it is '0'. And, what is 'x'?
>

The lambda keyword is merely another way to define a function.

As a general (and somewhat simplified rule),
    func = lambda <<1>>: <<2>>
is the same as
    def func(<<1>>):
        return <<2>>

The main difference is that lambda is an expression, while def is a
statement, which means you can use lambda is many places you cannot use
def, without adding extra lines of code.

>>> def make_incrementor(n):
> ...     return lambda x: x + n
> ...
> >>> f = make_incrementor(42)
> >>> f(0)
> 42
> >>> f(1)
> 43
>

Following the above rule, you can convert make_incrementor to look like:

def make_incrementor(n):
    def func(x):
        return x+n
    return func

That function, when called, will return a new function that takes one
argument, and adds it to the argument to make_incrementor.

n will be assigned what ever is passed into make_incrementor (42 in the
example code), and x will be what ever is passed into the returned function
(0 and 1 in the example).


> The second lambda example is even more obscure to me:
>
> >>> 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')]
>
>
> Could you explain 'key=lambda pair: pair[1]' to me?
>

In this case, you are passing a new "key" function into list.sort. Per the
documentation [1], the key function will be given each item in the input
list and should return the key to sort that item by. The lambda is defining
a function which takes one of those items (named pair inside the function),
and returns the second item (index 1) of it. list.sort then sorts the items
in the original list based on this key, whereby you get "four", "one",
"three", "two" sorted as strings, but the output will include the full
pairs.

This example could be rewritten as (again, following the general rule
mentioned at the top)"
>>> def keyFunc(pair):
>>>     return pair[1]
>>> pairs = [(1, 'one'), (2, 'two'), (3, 'three'), (4, 'four')]
>>> pairs.sort(key=keyFunc)
>>> pairs
[(4, 'four'), (1, 'one'), (3, 'three'), (2, 'two')]

[1] https://docs.python.org/2/howto/sorting.html#key-functions


> Python grammar seems too succinct to me.
>
>
> Thanks,
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20150602/10ba7765/attachment.html>


More information about the Python-list mailing list