Op 27-09-16 om 10:09 schreef cpx...@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)] -- https://mail.python.org/mailman/listinfo/python-list