I’m trying to return from a function a list of functions, each of which uses variables from the outside scope. This isn’t working. Here’s an example which demonstrates what’s happening:
a = []
for i in range(10):
a.append(lambda x: x+i)
a[1](1) # returns 10, where it seems it should return 2
Why is this happening, and how can I get around it in python 2.7 ?
The
irefers to the same variable each time, soiis 9 in all of the lambdas because that’s the value ofiat the end of the loop. Simplest workaround involves a default argument:This binds the value of the loop’s
ito a local variableiat the lambda’s definition time.Another workaround is to define a lambda that defines another lambda, and call the first lambda:
This behavior makes a little more sense if you consider this:
Here,
innerfuncis defined once, so it makes intuitive sense that you are only working with a single function object, and you would not expect the loop to create ten different closures. With a lambda it doesn’t look like the function is defined only once, it looks like you’re defining it fresh each time through the loop, but in fact it is functionally the same as the the long version.