In Python 2.7, running the following code:
def f():
a = a + 1
f()
gives the following result:
Traceback (most recent call last):
File "test.py", line 4, in <module>
f()
File "test.py", line 2, in f
a = a + 1
UnboundLocalError: local variable 'a' referenced before assignment
But if I change the code to below:
def f():
a[0] = a[0] + 1
f()
I get the different error:
Traceback (most recent call last):
File "test.py", line 4, in <module>
f()
File "test.py", line 2, in f
a[0] = a[0] + 1
NameError: global name 'a' is not defined
Why is Python considering a
is a local variable when it is an int
, global when list
? What's the rationale behind this?
P.S.: I was experimenting after reading this thread.