Can lists be mutated? [duplicate]

You created a new list object and bound it to the same name, x. You never mutated the existing list object bound to x at the start.

Names in Python are just references. Assignment is binding a name to an object. When you assign to x again, you are pointing that reference to a different object. In your code, you simply created a whole new list object, then rebound x to that new object.

If you want to mutate a list, call methods on that object:

x.append(2)
x.extend([2, 3, 5])

or assign to indices or slices of the list:

x[2] = 42
x[:3] = [5, 6, 7]

Demo:

>>> x = [1, 2, 3]
>>> id(x)
4301563088
>>> x
[1, 2, 3]
>>> x[:2] = [42, 81]
>>> x
[42, 81, 3]
>>> id(x)
4301563088

We changed the list object (mutated it), but the id() of that list object did not change. It is still the same list object.

Perhaps this excellent presentation by Ned Batchelder on Python names and binding can help: Facts and myths about Python names and values.

Leave a Comment