Today I explored a weird behavior of Python. An example:
closures = []
for x in [1, 2, 3]:
# store `x' in a "new" local variable
var = x
# store a closure which returns the value of `var'
closures.append(lambda: var)
for c in closures:
print(c())
The above code prints
3
3
3
But I want it to print
1
2
3
I explain this behavior for myself that var is always the same local variable (and python does not create a new one like in other languages). How can I fix the above code, so that each closure will return another value?
The easiest way to do this is to use a default argument for your lambda, this way the current value of
xis bound as the default argument of the function, instead ofvarbeing looked up in a containing scope on each call:Alternatively you can create a closure (what you have is not a closure, since each function is created in the global scope):
make_closure()could also be written like this, which may make it more readable: