lambda forms within a loop

Paul Rubin http
Sun Oct 25 16:42:11 EDT 2009


Michal Ostrowski <mostrows at 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.



More information about the Python-list mailing list