lambda in list comprehension acting funny
Alister
alister.ware at ntlworld.com
Thu Jul 12 05:44:15 EDT 2012
On Wed, 11 Jul 2012 08:43:11 +0200, Daniel Fetchinson wrote:
>> funcs = [ lambda x: x**i for i in range( 5 ) ]
>> print funcs[0]( 2 )
>> print funcs[1]( 2 )
>> print funcs[2]( 2 )
>>
>> This gives me
>>
>> 16 16 16
>>
>> When I was excepting
>>
>> 1
>> 2
>> 4
>>
>> Does anyone know why?
>
> And more importantly, what's the simplest way to achieve the latter? :)
Having read Steve's explanation in the other thread (which I think has
finally flipped the light switch on lambda for me) it only requires a
minor change
funcs=[ lambda x,y=i:x**y for i in range(5) ]
although I cant actually think why this construct would be needed in
practice, how are you actually using it
--
* Simunye is so happy she has her mothers gene's
<Dellaran> you better give them back before she misses them!
More information about the Python-list
mailing list