First thing first, lambda
s are anonymous functions. The form of a lambda
can be generalized to the following form:
lambda arguments: expression
So, I think rewriting the lambda
in myfunc()
will help you understand what's going on. If the lambda
were to be rewritten as a function:
def myfunc(n):
def lambda_as_func(a):
return a * n
return lambda_as_func
This snippet and your snippet, in essence, perform the same tasks: when myfunc()
is called, a function is returned. The returned function takes one argument (a
), which can be called later.
If you were to try it out:
>>> def myfunc(n):
def lambda_as_func(a):
return a * n
return lambda_as_func
>>> double = myfunc(2)
>>> double(11)
22
>>> double(50)
100
However, instead of defining another function within myfunc()
, Python allows us to create lambda_as_func()
as a one line function in the form as a lambda
.