If I make two lists of functions:
def makeFun(i): return lambda: i a = [makeFun(i) for i in range(10)] b = [lambda: i for i in range(10)]
why do lists a
and b
not behave in the save way?
For example:
>>> a[2]() 2 >>> b[2]() 9
Since a for loop is a statement (as is print , in Python 2. x), you cannot include it in a lambda expression.
A Python for loop is used to loop through an iterable object (like a list, tuple, set, etc.) and perform the same action for each entry. We can call a function from inside of for loop.
To create functions in a loop with Python, we can create a function that returns a function and call it. to define the make_f function that we can call in a loop to return a function. Then we can do whatever we want with the returned function.
Python allows lambda nesting, i.e., you can create another lambda function inside a pre-existing lambda function. For nesting lambdas, you will need to define two lambda functions – an outer and an inner lambda function. When the outer lambda is called, the inner lambda creates a function.
As others have stated, scoping is the problem. Note that you can solve this by adding an extra argument to the lambda expression and assigning it a default value:
>> def makeFun(i): return lambda: i ... >>> a = [makeFun(i) for i in range(10)] >>> b = [lambda: i for i in range(10)] >>> c = [lambda i=i: i for i in range(10)] # <-- Observe the use of i=i >>> a[2](), b[2](), c[2]() (2, 9, 2)
The result is that i
is now explicitly placed in a scope confined to the lambda
expression.
Technically, the lambda expression is closed over the i
that's visible in the global scope, which is last set to 9. It's the same i
being referred to in all 10 lambdas. For example,
i = 13 print b[3]()
In the makeFun
function, the lambda closes on the i
that's defined when the function is invoked. Those are ten different i
s.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With