Hi all,
I was trying to understand local and global arrays/lists in Python. Consider the following code snippets -
Code 1 -
def f():
a = np.append(a,3)
print(a)
a = np.array([12,3,4])
f()
print(a)
This gives a ‘local variable ‘a’ referenced before assignment’ error.
Code 2-
def f():
a.append(3)
print(a)
a =[12,3,4]
f()
print(a)
This prints [12,3,4,3] twice.
In both code 1 and code 2 a is a global variable. But with lists it is possible to change the value within f whereas other global variables do not allow their values to be changed within a function without the global keyword. I think this difference is because in case of lists f() knows the memory address whereas for arrays f() only knows the contents of it. Is this the right way to think about this ?
Thanking in advance for comments and suggestions.