Please consider the code below.
a = []
def func1(x):
return x
for i in range(3):
def func2():
return func1(i)
a.append(func2)
for k in range(3):
print(a[k]())
This prints out
2
2
2
From 'The use of aliases' in http://gestaltrevision.be/wiki/python/aliases (last section) and in 'Scope' section in http://gestaltrevision.be/wiki/python/functions_basics, I learnt that function parameters are actually aliases of arguments that are passed.
So according to that, in
def func1(x): return x
for i in range(3):
def func2(): return func1(i)
I reasoned since x would be stored as an alias to i, even though i is reassigned each time the loop is executed, it would not matter to its alias, x.
So I expected the first three lines to output 0, 1, 2 instead of 2, 2, 2.
Can you explain what I did wrong here? Thanks