it looks strange

Jussi Piitulainen jussi.piitulainen at helsinki.fi
Tue Sep 27 04:24:24 EDT 2016


cpxuvs at gmail.com writes:

>>>> li=[lambda :x for x in range(10)]
>>>> res=li[0]()
>>>> print res
> 9
>
> why?

Because each of the ten functions will report the final value of the
same x.

There are a couple of tricks to capture the transient value:

[lambda w=x: w for x in range(10)]

[(lambda w: (lambda :w))(x) for x in range(10)]

The former works because the default value of w is whatever x was when
the function object was created.

I think the latter does what you thought you were doing, but it's harder
to read and probably the difference should not matter much in practice.

You can call w x in both tricks if you like.



More information about the Python-list mailing list