Python Forum
help on understanding this output - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: help on understanding this output (/thread-2347.html)



help on understanding this output - landlord1984 - Mar-08-2017

>>> flist = []
>>> for i in range(3):
...     flist.append(lambda: i)
...
>>> [f() for f in flist]   # what will this print out?
Why is the above output [2,2,2]?

Thanks,

L


RE: help on understanding this output - zivoni - Mar-08-2017

Python uses "late binding" here. Lambda is defined with variable i, but actual value of i is looked up when that lambda is called. After for loop i is 2, so all lambdas return 2.

Common trick to avoid this is to use such variable as another parameter:

lambda x, i=i : x + i  # <- this binds i to actual value of i
In your case lambda i=i : i would work as "expected".