Michal Ostrowski <mostr...@gmail.com> writes: > def MakeLambdaBad(): > a = [] > for x in [1,2]: > a.append(lambda q: x + q) > return a
The problem here is that x is a free variable in the lambdas that you put in a. When you actually evaluate those lambdas, they use whatever the value of x happens to be at that time. The cure is: for x in [1,2]: a.append(lambda q, x=x: x + q) This creates an additional binding inside the lambda, that captures the value of the loop index when the lambda is made. -- http://mail.python.org/mailman/listinfo/python-list