Why global variable changes in function?

def test_func(a_global, b_global):
    a_local = a_global
    for i in range(len(a_local)):
        a_local[i] = i+1
    print("a_global: ", a_global)
    print("a_local: ", a_local)
    print()
    
    b_local = b_global
    c_local =[]
    for i in range(len(b_local)):
        c_local.append(i+1)
    b_local = c_local               #or b_local = [1,2,3,4,5]
    print("b_global: ", b_global)
    print("b_local: ", b_local)
    print()

    
a_global = [0,0,0,0,0]
b_global = [0,0,0,0,0]    

test_func(a_global, b_global)

output:

a_global:  [1, 2, 3, 4, 5]
a_local:  [1, 2, 3, 4, 5]

b_global:  [0, 0, 0, 0, 0]
b_local:  [1, 2, 3, 4, 5]

I had a problem and i found my solution but i dont know the reason. Do you have any advice to avoid the same situation again?

i have two global and two local variables. I’m assigning global variable to both local variables. In the first example i use for loop for assignin new values for local variable. In this case the global variable is also changing and I don’t want that.

my solution is the second example. If i use a third temporary variable and assign it to the local variable (or directly assign a new list) the global one doesn’t change.

I checked all the lines step by step and found the reason but i don’t want to experience similar situation again. I need your advices.

Answer

You could use copy() when assigning a_local = a_global.copy().

So:

def test_func(a_global, b_global):
a_local = a_global.copy()
for i in range(len(a_local)):
    a_local[i] = i+1
print("a_global: ", a_global)
print("a_local: ", a_local)
print()

b_local = b_global
c_local = []
for i in range(len(b_local)):
    c_local.append(i+1)
b_local = c_local  # or b_local = [1,2,3,4,5]
print("b_global: ", b_global)
print("b_local: ", b_local)
print()


a_global = [0, 0, 0, 0, 0]
b_global = [0, 0, 0, 0, 0]

test_func(a_global, b_global)

That will output the following:

a_global:  [0, 0, 0, 0, 0]
a_local:  [1, 2, 3, 4, 5]

b_global:  [0, 0, 0, 0, 0]
b_local:  [1, 2, 3, 4, 5]