Question on lambdas

Ben Finney ben+python at benfinney.id.au
Mon Dec 8 18:58:10 EST 2014


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’.

> 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.

-- 
 \       “Theology is the effort to explain the unknowable in terms of |
  `\                         the not worth knowing.” —Henry L. Mencken |
_o__)                                                                  |
Ben Finney




More information about the Python-list mailing list