Understand what a shallow copy is in Python, how to create one, and when to use it. Learn with beginner-friendly examples and comparisons to deep copy for nested objects.
In Python, a shallow copy is a new object that is a copy of the original object, but it does not create copies of nested objects (objects inside objects). Instead, it only copies references to those inner objects.
copy()
method (for lists, dicts, etc.):original = [[1, 2], [3, 4]]
shallow = original.copy()
copy
module:import copy
shallow = copy.copy(original)
import copy
original = [[1, 2], [3, 4]]
shallow = copy.copy(original)
shallow[0][0] = 100
print("Original:", original) # [[100, 2], [3, 4]]
print("Shallow:", shallow) # [[100, 2], [3, 4]]
✅ The outer list is copied.
❌ The inner lists are shared, so modifying shallow[0][0]
changes original[0][0]
.
Here’s a line-by-line explanation of the code:
import copy
✅ This imports Python’s built-in copy
module, which provides functions to perform shallow and deep copies.
original = [[1, 2], [3, 4]]
✅ A list named original
is created. It contains two inner lists, making it a nested list (a list of lists).
shallow = copy.copy(original)
✅ This creates a shallow copy of original
and stores it in shallow
.
So now:
original
and shallow
are two different outer lists.original[0]
and shallow[0]
point to the same inner list [1, 2]
.shallow[0][0] = 100
✅ This changes the first element of the first inner list through the shallow copy.
Since the inner list [1, 2]
is shared between original
and shallow
, the change affects both.
print("Original:", original) # [[100, 2], [3, 4]]
print("Shallow:", shallow) # [[100, 2], [3, 4]]
✅ Output shows that both original
and shallow
are affected:
Original: [[100, 2], [3, 4]]
Shallow: [[100, 2], [3, 4]]
copy.copy()
only copies the outer list.original
and shallow
.Use shallow copy when:
Tutorials, Roadmaps, Bootcamps & Visualization Projects