Possible Duplicate:
What do (lambda) function closures capture in Python?
With this code :
def problem():
PHI_LIST_0 = [lambda a, b: a+b+u for u in xrange(3)]
PHI_LIST_1 = [lambda a, b: a+b+0, lambda a, b: a+b+1, lambda a, b: a+b+2]
for phi in PHI_LIST_0: print "v0:", phi(1,1)
print
for phi in PHI_LIST_1: print "v1:", phi(1,1)
if __name__ == '__main__':
problem()
I get:
v0: 4
v0: 4
v0: 4
v1: 2
v1: 3
v1: 4
The expected behavior is the last one, with PHI_LIST_1. I think I understand why the results differ with PHI_LIST_0: maybe because Python uses the last 'u', ie 2, when phi(1,1) is evaluated.
But I would like to declare a list of functions the way PHI_LIST_0 is defined, with a list comprehension. Does anybody know how I could do that ?