This works:
A=[1]
B=A.copy()
print(B)
print(A)
print(B)
B.append(2)
print(B)
print(A)
print(B)
This does not:
A=[[1]]
B=A.copy()
print(B)
print(A)
print(B)
B[0].append(2)
print(B)
print(A) # Bad A here.
print(B)
A is getting modified. Any reason why?
Thanks,
Bassam
I'm assuming the inner lists for B are pointers, but why? Do I need to loop through each item to create a copy?
This is a mutable vs immutable thing. Everything in Python is an object. Some objects, like numbers and strings, are immutable, they cannot be modified. 2 is always 2 and "cat" is always "cat". Other objects, like lists and dictionaries, are mutable, they can be changed after they are created.
When you copy a list, a new list is created that contains the same objects as the old. B = A.copy() creates a new list that is assigned to B. The contents of list B are the same objects as those in list A.
In your first example, A contains a number, an immutable object. When you copy A, the new list contains the same object, an immutable number.
In the second example, A contains a list, [1]. When you copy A, the new list contains the same object as A, [1]. Both A and B contain the same list object. If you change that object it will look like both A and B changed, but the didn't. A abd B are the same as before, only the list object they have in common changed.
You can start with interactive interpreter:
>>> help(list.copy)
Help on method_descriptor:
copy(self, /)
Return a shallow copy of the list.
So the copy is shallow. What does it mean? From Python documentation:
Quote:Assignment statements in Python do not copy objects, they create bindings between a target and an object. For collections that are mutable or contain mutable items, a copy is sometimes needed so one can change one copy without changing the other.
/.../
The difference between shallow and deep copying is only relevant for compound objects (objects that contain other objects, like lists or class instances):
- A shallow copy constructs a new compound object and then (to the extent possible) inserts references into it to the objects found in the original.
- A deep copy constructs a new compound object and then, recursively, inserts copies into it of the objects found in the original.
Two problems often exist with deep copy operations that don’t exist with shallow copy operations:
- Recursive objects (compound objects that, directly or indirectly, contain a reference to themselves) may cause a recursive loop.
- Because deep copy copies everything it may copy too much, such as data which is intended to be shared between copies.