Mix lambda and list comprehension?

Peter Barth peter.barth at t-online.de
Tue Jul 15 11:32:38 EDT 2003


Thanks a lot, works fine.
However, the solution does not really feel "pythonesque".
Is it considered a usability bug or fine as is?
- Peter

"Raymond Hettinger" <vze4rx4y at verizon.net> wrote in message news:<hMNQa.1134$I4.740 at nwrdny01.gnilink.net>...
> 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