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?
From Ned Batchelder - Facts and Myths about Python names and values - PyCon 2015:
Functions like x.append("something")
and x.remove("something")
mutate a value, and change their values. However, using x=x+["something"]
or x=x[:-1]
rebind a reference, and create a new value which the variable now points to.
Thanks to @timgeb for commenting the video!