Sobes.tech
Junior — Middle

What is the difference between creating a full copy of an object and copying its references to internal objects?

sobes.tech AI

Answer from AI

Python has two main ways to copy objects: shallow copy and deep copy.

  • Shallow copy creates a new object but inner objects (like nested lists, dictionaries) are shared references. Changes in nested objects affect both copies.

  • Deep copy creates a new object and recursively copies all nested objects, resulting in a fully independent copy.

Example:

import copy

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

shallow[1].append(5)
print(original)  # [1, [2, 3, 5], 4] — nested list changed
print(shallow)   # [1, [2, 3, 5], 4]
print(deep)      # [1, [2, 3], 4] — deep copy unaffected

Deep copying is used when full independence of the copy from the original is needed, shallow copying when only the top level needs to be copied.