Below is an example I got from someone’s blog about python closure.
I run it in python 2.7 and get a output different from my expect.
flist = []
for i in xrange(3):
def func(x):
return x*i
flist.append(func)
for f in flist:
print f(2)
My expected output is: 0, 2, 4
But the output is: 4, 4, 4
Is there anyone could help to explain it?
Thank you in advance.
Loops do not introduce scope in Python, so all three functions close over the same
ivariable, and will refer to its final value after the loop finishes, which is 2.It seems as though nearly everyone I talk to who uses closures in Python has been bitten by this. The corollary is that the outer function can change
ibut the inner function cannot (since that would makeia local instead of a closure based on Python’s syntactic rules).There are two ways to address this: