lambda trouble

Elaine Jackson elainejackson7355 at home.com
Sat Mar 20 23:42:47 EST 2004


The problem, they say, is that a variable in a FOR clause can't bind a variable
inside a lambda abstraction. Fortunately the lambda operator itself doesn't
share this limitation, so you can make the variable visible to the binder in the
FOR clause by binding with a lambda and then evaluating the resulting
abstraction at the variable in question, like so:

>>> def p(x): print x
>>> list=[]
>>> for i in range(5): list.append((lambda j: lambda: p(j))(i))
>>> x=map(lambda f: f(),list)
0
1
2
3
4

Or, more concisely,

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





More information about the Python-list mailing list