I have a list of lambda functions I want to evaluate in order. I'm not sure why, but only the last function gets evaluated. Example below:
>>> def f(x,z):
... print "x=",x,", z=",z
...
>>>
>>> g = lambda x : f(x,13)
>>> g(2)
x= 2 , z= 13 # As expected
>>>
>>> lst=[]
>>>
>>> for i in range(0,5):
... lst.append(lambda x: f(x,i))
...
>>> print lst
[<function <lambda> at 0x10341e2a8>, <function <lambda> at 0x10341e398>, <function <lambda> at 0x10341e410>, <function <lambda> at 0x10341e488>, <function <lambda> at 0x10341e500>]
>>>
>>> for fn in lst:
... fn(3)
...
x= 3 , z= 4 # z should be 0
x= 3 , z= 4 # z should be 1
x= 3 , z= 4 # z should be 2
x= 3 , z= 4 # z should be 3
x= 3 , z= 4 # as expected.
I think only the last one is getting executed, but not the others. Any ideas? Thanks!
The lambda is just looking up the global value of 'i'.
Try the following instead:
for i in range(0,5):
lst.append(lambda x, z=i: f(x,z))
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