Artur Siekielski wrote: > Hello. > I found this strange behaviour of lambdas, closures and list > comprehensions: > > >>>> funs = [lambda: x for x in range(5)] >>>> [f() for f in funs] >>>> > [4, 4, 4, 4, 4] > > Of course I was expecting the list [0, 1, 2, 3, 4] as the result. The > 'x' was bound to the final value of 'range(5)' expression for ALL > defined functions. Can you explain this? Is this only counterintuitive > example or an error in CPython? > > > Regards, > Artur > Check this : >>> funs = [(lambda: x) for x in range(5)] >>> funs[0]() 4 >>> x 4 >>> x = 3 >>> funs[0]() 3 >>> del x >>> funs[0]() Traceback (most recent call last): File "<input>", line 1, in <module> File "<input>", line 1, in <lambda> NameError: global name 'x' is not defined
So you see, your functions just return the value of x. That's because the lambda have no parameter, so x refers to the global name x.
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor