Published on

9. Shallow copy vs of Deep copy

Authors

9. When should you use shallow copy instead of deep copy, and vice versa?

The decision between using a shallow copy and a deep copy depends on the structure of your data and how much independence you want between the copy and the original.


πŸ” Shallow Copy

A shallow copy creates a new outer object, but does not clone nested (inner) objects β€” it just copies references to them.

Use When:

  • Your data structure is flat (no nested objects).
  • You want a new container, but are okay sharing the same inner objects.
  • You care about performance and don’t need full independence.

Example:

import copy

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

shallow[2][0] = 99
print(original)  # [1, 2, [99, 4]] β€” original was affected!

🧬 Deep Copy

A deep copy creates a completely independent clone, recursively copying all nested objects.

Use When:

  • Your data contains nested structures (lists inside lists, dicts inside dicts, etc.).
  • You need full independence between the original and the copy.
  • You want to prevent accidental changes to shared nested objects.

Example:

import copy

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

deep[2][0] = 99
print(original)  # [1, 2, [3, 4]] β€” original remains unchanged

🧠 Summary:

FeatureShallow CopyDeep Copy
Copies outer object?βœ… Yesβœ… Yes
Copies inner objects?❌ No (shared references)βœ… Yes (fully independent)
PerformanceFasterSlower (recursive)
Use caseFlat or reference-safe dataNested or modification-sensitive data