In the following simplistic example variables x and y are assigned and passed into a function, where, under new names, they’re modified, summed and the result returned:
x,y = 2,3
def some_function(a,b):
z = a*2 + b*2
return z
z = some_function(x,y)
print(x, y, z)
> 2 3 10
Naturally, x and y have not changed, but that is what happens if they’re lists:
x = [[2,2]]
y = [[3,3]]
def some_function(a,b):
z = a + b # concatenate lists
for i in range(len(z)): # switch sign of 2nd elements
z[i][1] *= -1
return z
z = some_function(x,y)
print(f"z = {z}")
print(f"x (now) = {x}")
print(f"y (now) = {y}")
z = [[2, -2], [3, -3]] # perfectly correct
x (now) = [[2, -2]] # original lists have been changed(!?)
y (now) = [[3, -3]]
So passing lists to a function where they’re used with different variable names causes them to be altered? Never expected that, but it certainly explains the weird results I’m getting. I thought Python functions were supposed to create new local-only variables.
Note: The original lists are not and cannot be immutable. Later I will modify them, but I will need the originals to do that.
Can someone explain what’s going on here and how I can prevent my lists from being altered when passed to a function?