def mutation(input_list):
list_copy = input_list[:]
list_copy[0] = 10
input_list = list_copy
# Correctly mutates
sample_list = [0,1,2]
sample_copy = sample_list[:]
sample_copy[0] = 10
sample_list = sample_copy
print(sample_list)
# Incorrectly mutates
sample_list = [0,1,2]
mutation(sample_list)
print(sample_list)
In the top snippet of code, I've made a copy of a list and modified it. I then set the original to the copy and then it works. What confuses me is why doing this process outside of a function works but if I were to do it inside a function (the 2nd snippet of code), it fails?
For reference, the code returns:
[10, 1, 2]
[0, 1, 2]
EDIT: I know that calling input_list[0] = 10
works. I just want to know what makes this different from what I showed above all in memory?