Mix lambda and list comprehension?

Michele Simionato mis6 at pitt.edu
Tue Jul 15 08:41:02 EDT 2003


peter.barth at t-online.de (Peter Barth) 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

It is a scope issue. The last value for y is used for all
the created lambdas. All lambdas users are bitten by that,
soon or later. The solution is to make y local to the
lambda function, with the optional argument trick:

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

Michele




More information about the Python-list mailing list