Re: lambda in list comprehension acting funny
>>> funcs = [ lambda x: x**i for i in range( 5 ) ]
>>> print funcs( 2 )
>>> This gives me
>>> When I was excepting
>>> 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 ) ]
Thanks a lot!
I worked around it by
return lambda x: x**i
funcs = [ p(i) for i in range(5) ]
But your variant is nicer (matter of taste of course).
Psss, psss, put it down! - http://www.cafepress.com/putitdown
|All times are GMT. The time now is 07:56 AM.|
SEO by vBSEO ©2010, Crawlability, Inc.