Reputation: 4302
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?
Upvotes: 1
Views: 587
Reputation: 545
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.
Upvotes: 2
Reputation: 16619
Replace
>>> l1 = [2, 3, 4]
with
>>> l1[:] = [2, 3, 4]
That will not assign a new list to l1.
Upvotes: 0
Reputation: 49318
You are not mutating l1
. You are assigning a new object to the same name, which makes that name point to a new object. You are moving a label, not modifying an object. The only remaining reference to the list that l1
used to point to is now ans[0]
.
Upvotes: 3