Pradeep Vairamani Pradeep Vairamani - 1 month ago 4x
Python Question

Mutability of lists in python

Example one: Changing the value that has been appended to b changes the value in the original list l

>>> l = [1 , 2, 3]
>>> b = []
>>> b.append(l)
>>> b[0].append(4)
>>> b
[[1, 2, 3, 4]]
>>> l
[1, 2, 3, 4]

Example 2: l1 is appended to ans and then the value of l1 is modified. However, the value in ans remains the same.

>>> l1 = [1, 2, 3]
>>> ans = []
>>> ans.append(l1)
>>> ans
[[1, 2, 3]]
>>> l1 = [2, 3, 4]
>>> ans
[[1, 2, 3]]

I seem to be missing some fundamental point about the mutability of lists. Could someone please point it out?


In your first example, l is a pointer, as well as b.

l is then appended to b, so b[0] now refers to the pointer.

Next, you append 4 to b[0], which is the same thing as l, so 4 is added to both b[0] and l.

In your second example, ans contains the pointer of l1, just like b contained the pointer of l

Then, you changed l1 itself by assigning it to a different array, so l1 changed but ans[0] did not.

The biggest takeaway from this is that append just changes the list, and the pointer remains the same. But when you set a variable to a different list, the pointer changes.