If i were to run this code:
def function(y):
y.append('yes')
return y
example = list()
function(example)
print(example)
Why would it return ['yes'] even though i am not directly changing the variable 'example', and how could I modify the code so that 'example' is not effected by the function?
解决方案
Everything is a reference in Python. If you wish to avoid that behavior you would have to create a new copy of the original with list(). If the list contains more references, you'd need to use deepcopy()
def modify(l):
l.append('HI')
return l
def preserve(l):
t = list(l)
t.append('HI')
return t
example = list()
modify(example)
print(example)
example = list()
preserve(example)
print(example)
outputs
['HI']
[]