it looks strange

Antoon Pardon antoon.pardon at rece.vub.ac.be
Tue Sep 27 04:36:53 EDT 2016


Op 27-09-16 om 10:09 schreef cpxuvs at gmail.com:
>>>> li=[lambda :x for x in range(10)]
>>>> res=li[0]()
>>>> print res
> 9
>
> why?

Because there is no nested scope for the x variable.So your list looks
like this: [lambda :x, lambda :x, lambda :x, lambda :x, lambda :x,
lambda :x, lambda :x, lambda :x, lambda :x, lambda :x] with x having the
value 9, being the last value through the loop. So your code is
quivallent to the following. >>> li=[lambda :x for t in range(10)]
>>> x = 9

What you probably want is the following:

>>> li = [(lambda t: lambda :t)(x) for x in range(10)]




More information about the Python-list mailing list