I'm calling a function in Python 3.7.x and passing a list to it. I do not want the list modified. Inside the function, I make a copy of the list and modify that.
After the function completes, the original list passed to the function has been modified. Why is that happening and how can I prevent it?
Here is the code
def append_string(alist, astring):
a_new_list = alist
a_new_list.append(astring)
return a_new_list
my_list = ["a", "b"]
my_string = "c"
my_new_list = append_string(my_list, my_string)
print(my_list)
print(my_new_list)
Here is the output. Notice that my_list
has been modified.
['a', 'b', 'c']
['a', 'b', 'c']
I would have expected my_list
to remain unmodified and the my_new_list
to contain the concatenation of the values.