Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What exactly is happening when I copy and then edit this list?

I cannot figure out at all why this is happening:

A = [[1,0], [2,2]]
B = list(A)

print('start A:', A, 'start B:', B)
A[0][0] = 999
print('end A:', A, 'end B:', B)

This returns:

start A: [[1, 0], [2, 2]] start B: [[1, 0], [2, 2]]
end A: [[999, 0], [2, 2]] end B: [[999, 0], [2, 2]]

The lists A and B end up being the same, even though I explicitly copied B from A. This only happens when I do something like A[0][0] = 999; if I replace that with A[0] = 999 then A and B are different at the end.

What's the reason behind this, and is there any way to change A in this manner without affecting B?

like image 574
kennysong Avatar asked Feb 22 '23 07:02

kennysong


2 Answers

You are creating a shallow copy of the original list, that is a new list containing new references to the same objects as the original list.

Modifying the new list object does not alter the original list. Modifying the objects in the new list does modify the objects in the old list because they are the same.

To get a completely separate list, use copy.deepcopy() to create a deep copy.

like image 184
Sven Marnach Avatar answered Apr 07 '23 00:04

Sven Marnach


Both A and B contain the same two lists.

Your code is roughly equivalent to this:

x = [1, 0]
y = [2, 2]

A = [x, y]
B = [x, y]

The operation A[0][0] = 999 is effectively just doing x[0] = 999. That is, it doesn't modify A itself, it modifies the first element of the list x. Since both A and B have references to x, both will see the change.

like image 24
Mark Byers Avatar answered Apr 07 '23 00:04

Mark Byers