Copying in Python
Case 1
Say we have a list, x = [1, 2, 3, 4]
If we use y = copy(x) and y = deepcopy(x) for ‘x’, it will have the same effect.
Case 2
But if we have, x = [1, 2, [3], 4]
If we use y = copy(x) and y = deepcopy(x) for this, only deepcopy will have the desired effect.
For y = copy(x) in this case,
if we do y[2].append(1)
then x = [1, 2, [3, 2], 4] and y = [1, 2, [3, 2], 4]
While for y = deepcopy(x),
if we do y[2].append(1)
then x = [1, 2, [3], 4] and y = [1, 2, [3, 2], 4] which is the desired effect.
This is because if we use copy, the 2nd index of y still holds a reference to x’s object (the list at the 2nd index), while for deepcopy, even the list gets copied and a new address in memory is created for it during the deepcopy.