While writing a recursive function in python, I noticed an interesting phenomenon. .append
will change an input variable, but =
creates a private instance variable in the function. For example, using equals does not affect a,
>>> def f(x):
x=x[:-1]
>>> a=[1, 2, 3]
>>> f(a)
>>> a
[1, 2, 3]
while using append changes a.
>>> def g(x):
x.remove(3)
>>> g(a)
>>> a
[1, 2]
>>>
I assume this is because .remove
edits the reference, while [:-1]
creates a new list, but is there a reason why this occurs?