In Python 2.7, the following code is executed:
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 below:
def f(): a[0] = a[0] + 1 f()
I get a 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 given a a local variable if it is int , global when list ? What is the reason for this?
PS: I experimented after reading this topic .
source share