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']
[]