Consider this function:
def g():
x = []
def f():
x.append([0])
print(x)
pass
return f
Calling it:
test = g()
test()
I get the following output:
Out: [[0]]
We can reinitialize the test function and call it multiple times:
test = g()
for i in range(3):
test()
Resulting in the following output:
Out: [[0]]
[[0], [0]]
[[0], [0], [0]]
However, defining the following function:
def j():
x = 1
def f():
x += 1
print(x)
pass
return f
And calling it:
test = j()
test()
Results in an error:
UnboundLocalError: local variable 'x' referenced before assignment
The list seems to be in the inner function scope while the value is not. Why is this happening?