for x in fruits: print(x) func = lambda: print(x) print(func) my_funcs.append(func)
for func in my_funcs: func()
1 2 3 4 5 6 7 8 9 10
apple <function <lambda> at 0x7faa99aef940> banana <function <lambda> at 0x7faa99aef9d0> tangerine <function <lambda> at 0x7faa99aefa60> coconut <function <lambda> at 0x7faa99aefaf0> cherry <function <lambda> at 0x7faa99aefb80>
It seems both the lambda functions and their argument varies in each loop, but it prints the same string all the time.
This happens because x is not local to the lambdas, but is defined in the outer scope, and it is accessed when the lambda is called — not when it is defined.
In the above example, the scope of x is the for loop. When lambda is defined, the x is a reference to the variable in the loop, not a constant value, so when the lambda is called later, the x will always be cherry – it is the value in the last iteration of the loop.