lambda in list comprehension acting funny

Ian Kelly ian.g.kelly at gmail.com
Wed Jul 11 18:34:33 CEST 2012


On Wed, Jul 11, 2012 at 4:28 AM, Colin J. Williams <cjw at ncf.ca> wrote:
> I don't understand why you would expect 1, 2, 4.

Because:

funcs[0](2) == 2 ** 0 == 1
funcs[1](2) == 2 ** 1 == 2
funcs[2](2) == 2 ** 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

No, that gives 16, 16, 16 just like the original.  I don't understand
why you would expect 1, 16, 81, unless you have misread the code.



More information about the Python-list mailing list