1

I want to define a function with a list x being its input variable, assume that I want to make the value of the input variable (x) unchanged after performing the function, what I thought I should do is to assign the value of the input variable (x) to another variable (y) and do the calculations on this new variable (y) and return y at the end keeping the input variable x untouched (this is the second function in the code).

Implementing that code gives the same results as if I've not added a new variable y and performed the calculations on y. The value of x is changed. (It gives the same results as the first function)

I've found that assigning the value of x to y indirectly by constructing an empty list y and then adding entries of x one by one to y and then performing the operation on y solves the problem (as in the third function in the code).

My question is, why do python do that? Shouldn't it be the case that when I assigned the value of x to y and do calculations on y that x stay unchanged? what am I missing?

def li(X):
   X.append(1)
   return(X)

def le(X):
   Y=X
   Y.append(1)
   return(Y)

def lo(X):
   Y=[]
   for i in range(X):
          Y.append(X[i])
   Y.append(1)
   return(X)
Fawzy Hegab
  • 137
  • 1
  • 2
  • 7

1 Answers1

3

what am I missing?

You're problem lies in the way Python's variables work. You see, when you assign the list x to the variable y, your not creating a copy of x. Rather your creating a reference to the list x. This means that when either variable changes(x or y), they both change because they both point to the exact same list.

You need to explicitly tell Python to create a copy of x, to the variable y. That way, both variable will be independent of each other:

>>> x = [1, 2, 3]
>>> 
>>> def change(x):
...     y = x[:] # create a copy of x and not a reference
...     y.append(4) # change the copy
...     return y
... 
>>> x # before change
[1, 2, 3]
>>> change(x)
[1, 2, 3, 4]
>>> x # after change
[1, 2, 3]
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87