Question on lambdas

MRAB python at mrabarnett.plus.com
Mon Dec 8 20:40:42 EST 2014


On 2014-12-08 23:58, Ben Finney wrote:
> memilanuk <memilanuk at gmail.com> writes:
>
>> What I'm having trouble finding a concrete answer to is the difference
>> between:
>
> (Note that where you write “some_func” the syntax requires an
> expression, not a function. I've changed your examples to be clear).
>
>> lambda: some_expr
>
> This creates a new function which expects zero parameters. The function,
> when called, will return the value of ‘some_expr’.
>
>> lambda x: some_expr
>
> This creates a new function which expects one positional parameter named
> ‘x’. The function, when called, will return the value of ‘some_expr’.
>
>> lambda x=some_value: some_expr
>
> This creates a new function which expects one parameter named ‘x’, which
> parameter has a default value of ‘some_value’. The function, when
> called, will return the value of ‘some_expr’.
>
This is useful when you want to 'capture' the current value of
'some_value' to be passed to some_expr; if you didn't, then some_expr
would be using the value of 'some_value' at the time it was called,
which might be different if some variable it used had been changed.

>> Any help would be greatly appreciated.
>
> Hope that helps.
>
> It's best to remember that ‘lambda’ is syntactic sugar for creating a
> function; the things it creates are not special in any way, they are
> normal functions, not “lambdas”.
>
> What is different is that the function starts with no name bound to it,
> and the syntax allows only a single expression as the body of the
> function.
>




More information about the Python-list mailing list