Velocity Reviews

Velocity Reviews (http://www.velocityreviews.com/forums/index.php)
-   Python (http://www.velocityreviews.com/forums/f43-python.html)
-   -   Re: lambda in list comprehension acting funny (http://www.velocityreviews.com/forums/t948005-re-lambda-in-list-comprehension-acting-funny.html)

Jurko Gospodnetić 07-11-2012 07:01 AM

Re: lambda in list comprehension acting funny
 
Hi.

>> funcs = [ lambda x: x**i for i in range( 5 ) ]
>> print funcs[0]( 2 )
>>
>> This gives me
>> 16
>>
>> When I was excepting
>> 1
>>
>> Does anyone know why?


Just the way Python lambda expressions bind their variable
references. Inner 'i' references the outer scope's 'i' variable and not
its value 'at the time the lambda got defined'.


> And more importantly, what's the simplest way to achieve the latter? :)


Try giving the lambda a default parameter (they get calculated and
have their value stored at the time the lambda is defined) like this:
funcs = [ lambda x, i=i: x**i for i in range( 5 ) ]


Hope this helps.

Best regards,
Jurko Gospodnetić



All times are GMT. The time now is 12:40 AM.

Powered by vBulletin®. Copyright ©2000 - 2014, vBulletin Solutions, Inc.
SEO by vBSEO ©2010, Crawlability, Inc.