lambda in list comprehension acting funny
Colin J. Williams
cjw at ncf.ca
Wed Jul 11 06:28:44 EDT 2012
On 11/07/2012 2:41 AM, 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?
>
> Cheers,
> Daniel
>
>
I don't understand why you would expect 1, 2, 4.
Perhaps parentheses will help the order of evaluation:
funcs = [(lambda x: x**i) for i in range( 5 )]
This gives:
1
16
81
Colin W.
More information about the Python-list
mailing list