I have an array of functions, for example:
>>> def f():
... print "f"
...
>>> def g():
... print "g"
...
>>> c=[f,g]
Then i try to create two lambda functions:
>>> i=0
>>> x=lambda: c[i]()
>>> i+=1
>>> y=lambda: c[i]()
And then, call them:
>>> x()
g
>>> y()
g
Why c[i] in lambda are the same?
lambda
s in the first place. Just replace those two lines withx = c[i]
andy = c[i]
, and you will get exactly the functions you wanted. The only reason to ever writelambda: f()
instead off
is to stickf
into a closure namespace to look it up later, instead of just using it. You don't want to do that here, and in fact that's exactly what's causing your problem. – abarnert May 26 '13 at 23:15