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?
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.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With