Evaluating A List Of Python Lambda Functions Only Evaluates The Last List Element
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): ... prin
Solution 1:
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))
Solution 2:
try using partial, works for me:
from functools import partial
deff(x,z):
print"x=",x,", z=",z
lst = [ partial(f,z=i) for i inrange(5) ]
for fn in lst:
fn(3)
http://docs.python.org/library/functools.html#functools.partial
Solution 3:
Not a Python expert, but is it possible that Python is treating i
in
lst.append(lambda x: f(x,i))
as a reference? Then, after the loop, i
is equal to its last assigned value (4), and when the functions are called, they follow their i
reference, find 4, and execute with that value.
Disclosure: probably nonsense.
Post a Comment for "Evaluating A List Of Python Lambda Functions Only Evaluates The Last List Element"