Given this piece of code(python)
s = [None]*10
def func():
for i in range(10):
def update():
print i,
s[i] = update
func()
for i in range(10):
s[i]()
why this result is ten 9s, instead of 0,1,2,3,…9 ?
btw, I’ve also print s[0]~s[9],which are 10 function addresses, and there are different from each other.
You’ve created a bunch of closures over
i, but they are all sharing the same (final) value ofiYou need to make a tiny modification like this