Given this snippet of code:
funcs = []
for x in range(3):
funcs.append(lambda: x)
print [f() for f in funcs]
I would expect it to print [0, 1, 2]
, but instead it prints [2, 2, 2]
. Is there something fundamental I'm missing about how lambdas work with scope?
1 Scope of a Lambda Expression. The body of a lambda expression has the same scope as a nested block. The same rules for name conflicts and shadowing apply. It is illegal to declare a parameter or a local variable in the lambda that has the same name as a local variable.
A variable is only available from inside the region it is created. This is called scope.
Simply put, a lambda function is just like any normal python function, except that it has no name when defining it, and it is contained in one line of code. A lambda function evaluates an expression for a given argument.
Lambda functions are inline functions and thus execute comparatively faster. Many times lambda functions make code much more readable by avoiding the logical jumps caused by function calls.
This is a frequent question in Python. Basically the scoping is such that when f()
is called, it will use the current value of x
, not the value of x
at the time the lambda is formed. There is a standard workaround:
funcs = []
for x in range(10):
funcs.append(lambda x=x: x)
print [f() for f in funcs]
The use of lambda x = x
retrieves and saves the current value of x
.
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