Introduction
When working with lists, dictionaries, or other complex objects in Python, you’ll often need to copy them. However, copying in Python isn’t always as simple as it looks. If you’re not careful, you might end up with unexpected behavior where changing one object also changes another.
This happens because Python offers two types of object copies:
Shallow Copy
Deep Copy
In this article, we’ll break down the difference between shallow copy and deep copy in simple terms, with examples, a visual infographic, and a skill challenge to make learning fun and interactive.
What is a Shallow Copy?
A shallow copy creates a new object, but it only copies references of the inner objects (not the actual inner objects themselves).
This means changes to nested objects will still reflect in both the original and the copy.
Example:
import copy
# Original list with nested list
original = [[1, 2, 3], [4, 5, 6]]
# Shallow copy
shallow_copied = copy.copy(original)
# Modify nested list
shallow_copied[0][0] = 99
print("Original:", original)
print("Shallow Copy:", shallow_copied)
Output:
Original: [[99, 2, 3], [4, 5, 6]]
Shallow Copy: [[99, 2, 3], [4, 5, 6]]Notice that modifying the shallow copy also changed the original. This is because only the outer list was copied, but the inner lists were still shared.
What is a Deep Copy?
A deep copy creates a new object and recursively copies all the nested objects inside it. This way, the new object is completely independent of the original.
👉 Changes in one object will not affect the other.
Example:
import copy
# Original list with nested list
original = [[1, 2, 3], [4, 5, 6]]
# Deep copy
deep_copied = copy.deepcopy(original)
# Modify nested list
deep_copied[0][0] = 99
print("Original:", original)
print("Deep Copy:", deep_copied)
Output:
Original: [[1, 2, 3], [4, 5, 6]]
Deep Copy: [[99, 2, 3], [4, 5, 6]]
Here, modifying the deep copy did not affect the original. That’s the power of deep copy.
Key Differences Between Shallow Copy and Deep Copy
| Feature | Shallow Copy | Deep Copy |
|---|---|---|
| Copy Type | Copies only outer object | Copies outer and all nested objects |
| Nested Objects | Still shared (changes affect both) | Fully independent (changes don’t affect each other) |
| Speed | Faster (less memory overhead) | Slower (more memory used) |
| Module Used | copy.copy() | copy.deepcopy() |

Join the conversation! Your thoughts help the community grow.