Sobes.tech
Middle

What is Shallow Copy and Deep Copy?

sobes.tech AI

Answer from AI

Shallow Copy creates a new object, but nested objects within it are not copied; they are simply referenced to the same objects as in the original.

Deep Copy creates a new object and recursively copies all nested objects, so the copy is completely independent of the original.

Example in Python:

import copy

original = [1, [2, 3], 4]
shallow = copy.copy(original)
deep = copy.deepcopy(original)

shallow[1][0] = 'changed'
print(original)  # [1, ['changed', 3], 4] — nested object has changed

deep[1][0] = 'deep changed'
print(original)  # [1, ['changed', 3], 4] — original remains unchanged

It is evident here that with shallow copy, the nested list changes in the original as well, whereas with deep copy, it does not.