Search code examples
pythonfunctionparametersparameter-passing

Function changes value of variable given as parameter


I have the following function:

def myfunc(x):
    y = x
    y.append(' appendix') # change happens here
    return y

x = []
z = myfunc(x)
print(x) # change is reflected here, and appendix is printed

how can I assure that changes x aren't reflected in the code that calls the function?


Solution

  • You do:

    y = x[:]
    

    to make a copy of the collection in x. Note that this is a shallow copy, so if the elements in the collection are mutable then those values can still be changed by the function - but for a list of characters this will work fine. For strings - immutable in Python - the copy is not required.