Mix lambda and list comprehension?

Raymond Hettinger vze4rx4y at verizon.net
Tue Jul 15 03:09:01 EDT 2003


Try this:

>>> [lambda x, y=y:x+y for y in range(10)][4](2)
6


It is important to bind y in a closure at the time
the lambda is defined.  Otherwise, y remains unbound
until you invoke the function call.  At that time, the most
recent value of y is the last value in the range loop (namely, 9).


Raymond Hettinger



"Peter Barth" <peter.barth at t-online.de> wrote in message
news:6f5b3f88.0307142302.1a1531f3 at posting.google.com...
> Hi,
> trying to mix lambda expresions and list comprehension
> doesn't seem to work.
> ---
> >>> [lambda x:x+y for y in range(10)][9](2)
> 11
> >>> [lambda x:x+y for y in range(10)][4](2)
> 11
> ---
> I expected the second expression to return 6.
> What did I do wrong? Any hints?
> Thanks
> - Peter






More information about the Python-list mailing list