Reputation: 1379
In Python, I find the following behavior of function related to the variable scope somewhat puzzling. It seems that a function can alter an element of an array outside of the function but not replace the array completely. What is this operating principle?
a = np.array([2,3,5])
b = np.array([2,3,5])
def fun1():
a[1] = 100
return
def fun2():
b = -1.1
return
fun1()
print(a)
fun2()
print(b)
Upvotes: 0
Views: 62
Reputation: 172
Python scope go in the LEGB order, First checking Local, Enclosing, Global Scope, and Bult-in scope When you search inside a array element, python searchs for a existing variable and references it, since there is no variable inside the function scope it goes to up in the scope
def fun3():
c[0] = 0
return
fun3 would print a error C is not defined wouldn't make c = [0], it would try to find the variable C first in the local scope (inside the function in the case) after it will go up in scope for each search
but when you do b = 1.1, it is going straight to assigning the variable it prioritizes the local scope and simple define its value inside the function
def fun5():
b = -1.1
print(b) # prints local value, -1.1
return
print(b) #prints original array)
in the mean while
def fun6():
b = [2,3,4]
b[1] = 500
print(b) #would print [2,500,4]
return
print(b) #would print original array
now in fun6 since the new b array is in inside the scope, the b[1] operation references the local scope first, and them only changes the local array without changing the original b array this happens because its the closer reference to b is in the local scope. if you comment the first line, the next closer reference would be the original b declared in the beginning of the file therefore the change would affect the variable b of that scope
user juanpa.arrivillaga also mentioned it on a reply first
Upvotes: 1