lambda trouble

Michele Simionato michele.simionato at
Sun Mar 21 12:52:48 CET 2004

"Elaine Jackson" <elainejackson7355 at> wrote in message news:<b397c.868228$X%5.57128 at pd7tw2no>...
> The problem, they say, is that a variable in a FOR clause can't bind a variable
> inside a lambda abstraction. 

I find this explanation confusing. It is just a matter of times:
the lambda uses the value of the bound name at *calling* time, not at
*definition* time:

>>> i=1
>>> f=lambda : i # definition time, i=1
>>> i=2
>>> f() # calling time, i has been rebound to 2

> >>> def p(x): print x
> >>> list=[(lambda j: lambda: p(j))(i) for i in range(5)]
> >>> x=map(lambda f: f(),list)

This works since the inner lambda uses the value of j at the calling time
of the outer lambda.

Just to clarifify the point for the OP, since I am sure you understand
the all story ;)

                  Michele Simionato

More information about the Python-list mailing list