Mix lambda and list comprehension?

Bengt Richter bokr at oz.net
Wed Jul 16 17:05:26 CEST 2003


On 15 Jul 2003 05:41:02 -0700, mis6 at pitt.edu (Michele Simionato) wrote:

>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

or you could capture y as constants in the lambdas ;-)

 >>> [eval('lambda x:x+%s'%y) for y in range(10)][4](2)
 6


Regards,
Bengt Richter




More information about the Python-list mailing list