Python Mastery – From Basics to Brilliance / Data Structures in Python

Shallow Copy vs Deep Copy

🟑 Shallow Copy

A shallow copy creates a new outer object, but the nested objects are still shared.

Use copy.copy():

import copy

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

shallow[0][0] = 100

print(original) #[[100, 2], [3, 4]]

Why? Both original and shallow refer to the same nested lists.

original ──→ [ [1, 2], [3, 4] ]
               ↑
shallow  β”€β”€β”€β”€β”€β”€β”˜

🟒 Deep Copy

A deep copy creates a completely independent copy, including the nested objects.

Use copy.deepcopy():

import copy

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

deep[0][0] = 100

print(original) #[[1, 2], [3, 4]]

The nested lists are copied as well.

original ──→ [ [1, 2], [3, 4] ]

deep ──────→ [ [1, 2], [3, 4] ]

They are completely independent.


βš–οΈ Shallow vs Deep Copy

Shallow Copy 🟑

Deep Copy 🟒

Creates a new outer object

Creates a completely independent copy

Nested objects are shared

Nested objects are also copied

copy.copy()

copy.deepcopy()

Changes to nested objects can affect original

Changes do not affect original

⭐ Remember

Shallow Copy     β†’ New outer object + Shared inner objects

Deep Copy        β†’ New outer object + New inner objects

For simple, non-nested objects, the difference usually doesn't matter. The distinction becomes important when working with nested mutable objects like lists and dictionaries.