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?

By : kennysong


A simple copy operation like you did is shallow, it only copies the items one level deep and does not recurse into nested structures. You need

A and B are two different names for the same chunk of memory within your computer.

A and B are two separate list objects, but A[0] and B[0] are two different names for the same chunk of memory within your computer. Try the following from the interpreter:


Python code manipulates references to objects.

Assigning to a variable is just binding a name to refer to an object.

A list consists of a bunch of references to objects. list(A) finds all the objects referenced in A and makes a new list with references to all the same objects. So if A is a list of lists, list(A) makes a new list with references to the same lists that were in A. So changing any of the sub-lists will be visible from both A and the new list.

copy.deepcopy exists to help you get around this, when you need a full "deep" copy of something.

Once you learn to think about Python code as manipulating references to objects like this, you will intuitively understand when code is likely to end up referring to the same object from multiple places like this, though there will probably always be obscure cases that surprise you.

By : Ben

This video can help you solving your question :)
By: admin