Python Shallow vs Deep Copy: Differences, Examples, and Pitfalls
A shallow copy creates a new outer container but still shares nested objects with the original. A deep copy creates a new outer container and also copies the nested objects, so the result is fully independent. The choice matters most when your data contains lists, dictionaries, or custom objects inside other containers.
Difficulty: Intermediate
Helpful to know first: basic Python variables, mutable and immutable objects, and how lists and dictionaries store references.
When to Use a Shallow Copy or a Deep Copy
- Use a shallow copy when you want a new top-level container, but sharing nested objects is acceptable.
- Use a deep copy when you need a completely independent structure, including all nested containers.
- Use neither when you actually want two names to refer to the same object.
| Topic | Shallow copy | Deep copy |
|---|---|---|
| New outer object | Yes | Yes |
| Nested objects copied | No | Yes |
| Shared references remain | Yes, for inner objects | No, for copied parts |
| Typical use | Small changes to a top-level container | Independent duplicate of nested data |
How Shallow Copy Works in Python
A shallow copy duplicates only the first level of a container. If the container holds other mutable objects, both the original and the copy still point to the same inner objects. That is why changing a nested list or dictionary often changes both versions.
Python gives you a few common ways to make a shallow copy. For lists, list.copy(), slicing, and copy.copy() all create a new outer list. For dictionaries, dict.copy() and copy.copy() do the same thing.
Shallow copy of a list with nested data
This example shows the key idea: the outer list is new, but the inner list is shared.
from copy import copy
original = [[1, 2], [3, 4]]
shallow = copy(original)
shallow[0].append(99)
print(original)
print(shallow)
# Output:
# [[1, 2, 99], [3, 4]]
# [[1, 2, 99], [3, 4]]The outer list changed into a separate object, but both lists still point to the same inner list at index 0. Changing that inner list updates both containers.
Shallow copy of a dictionary
Dictionary copying behaves the same way. The key-value pairs in the outer dictionary are copied, but nested lists remain shared.
from copy import copy
original = {"names": ["Ada", "Grace"]}
shallow = copy(original)
shallow["names"].append("Linus")
print(original)
print(shallow)
# Output:
# {'names': ['Ada', 'Grace', 'Linus']}
# {'names': ['Ada', 'Grace', 'Linus']}This is why a shallow copy is often enough for flat data, but risky for nested mutable data.
Shallow copy with assignment is not a copy
Many beginners think = makes a copy. It does not. It only creates another name for the same object.
a = [1, 2]
b = a
b.append(3)
print(a)
print(b)
# Output:
# [1, 2, 3]
# [1, 2, 3]Assignment does not duplicate anything. Both names refer to the same list object, so any change through one name appears through the other.
How Deep Copy Works in Python
A deep copy recursively copies the outer object and everything inside it that can be copied. The result is a separate structure, so you can change nested data in one copy without affecting the other.
Python provides deep copying through copy.deepcopy() in the standard library copy module. It is the standard tool for this job.
Deep copy of nested lists
Here the inner list is duplicated too, so the two outer lists no longer share nested data.
from copy import deepcopy
original = [[1, 2], [3, 4]]
deep = deepcopy(original)
deep[0].append(99)
print(original)
print(deep)
# Output:
# [[1, 2], [3, 4]]
# [[1, 2, 99], [3, 4]]Now the original stays unchanged because the nested list inside deep is a different object.
Deep copy of a custom object
Deep copy is also useful with user-defined classes that store mutable fields. The copied object gets its own nested state.
from copy import deepcopy
class Cart:
def __init__(self, items):
self.items = items
cart1 = Cart(["apple", "bread"])
cart2 = deepcopy(cart1)
cart2.items.append("milk")
print(cart1.items)
print(cart2.items)
# Output:
# ['apple', 'bread']
# ['apple', 'bread', 'milk']This works because deepcopy copies the object and also copies the list stored in its items attribute.
Deep copy of a mixed structure
Deep copy is most useful when a structure contains several layers of mutable data. A flat structure often does not need it, but nested records usually do.
from copy import deepcopy
data = {
"team": [
{"name": "Ada", "skills": ["python", "math"]},
{"name": "Grace", "skills": ["systems"]}
]
}
copy_data = deepcopy(data)
copy_data["team"][0]["skills"].append("algorithms")
print(data["team"][0]["skills"])
print(copy_data["team"][0]["skills"])
# Output:
# ['python', 'math']
# ['python', 'math', 'algorithms']That is the clearest sign that deep copy did its job: the nested list in the copy can change without touching the original.
Side by Side: The Differences That Matter
| Dimension | Shallow copy | Deep copy |
|---|---|---|
| Outer object | New object | New object |
| Inner mutable objects | Shared | Copied recursively |
| Speed | Usually faster | Usually slower |
| Memory use | Lower | Higher |
| Safe for nested mutation | No | Yes |
| Best for | Flat or mostly read-only data | Complex nested data that must be independent |
A shallow copy is often enough when the top-level container changes but the nested objects do not. A deep copy costs more because it has to walk the object graph and duplicate more data.
What changes and what stays shared
With a shallow copy, the container changes but the contents may still be shared. With a deep copy, the contents are duplicated too, unless Python deliberately reuses immutable objects like strings and integers.
from copy import copy, deepcopy
original = [[1], [2]]
shallow = copy(original)
deep = deepcopy(original)
print(original is shallow)
print(original[0] is shallow[0])
print(original[0] is deep[0])
# Output:
# False
# True
# FalseThe outer list is different in both cases, but only the deep copy breaks the link to the inner list.
Common Mistakes When Choosing a Copy
Using assignment when you wanted a copy
New Python users often write one variable name and assume it duplicates the data. That creates a reference, not a copy.
Problem: Both names point to the same list, so a change through one name changes the other.
first = [10, 20]
second = first
second.append(30)
print(first)
# Output: [10, 20, 30]Fix: Use a shallow copy for a flat list, or a deep copy if the list contains nested mutable objects.
from copy import copy
first = [10, 20]
second = copy(first)
second.append(30)
print(first)
# Output: [10, 20]The fixed version works because copy() creates a new outer list.
Using a shallow copy for nested mutable data
A shallow copy looks safe until you mutate something inside it. Then the original changes too.
Problem: The inner list is shared, so appending to the nested data affects both objects.
from copy import copy
original = [[1], [2]]
copy_list = copy(original)
copy_list[0].append(99)
print(original)
# Output: [[1, 99], [2]]Fix: Use deepcopy() when you need nested independence.
from copy import deepcopy
original = [[1], [2]]
copy_list = deepcopy(original)
copy_list[0].append(99)
print(original)
# Output: [[1], [2]]The corrected version works because each nested list is copied too.
Using the wrong copy method for the container type
Some objects support copy() directly, while others need the copy module. Beginners sometimes call a method that does not exist.
Problem: A tuple does not have a copy() method, so the code fails with an attribute error.
data = (1, 2, 3)
result = data.copy()
# AttributeError: 'tuple' object has no attribute 'copy'Fix: Use copy.copy() for a shallow copy, or just reuse the tuple if you do not need a new object. Tuples are immutable, so copying them is usually unnecessary.
from copy import copy
data = (1, 2, 3)
result = copy(data)
print(result)
# Output: (1, 2, 3)The corrected version works because the standard library function handles more object types than a method call on the object itself.
Predict the Output
Snippet 1: nested list aliasing
What does this print?
from copy import copy
items = [[1], [2]]
other = copy(items)
other[0].append(3)
print(items)Show answer
The output is [[1, 3], [2]]. The shallow copy creates a new outer list, but both lists still share the inner list at index 0. Appending to that inner list changes the shared object, so the original changes too.
Snippet 2: deep copy breaks the link
What does this print?
from copy import deepcopy
data = [{"count": 1}]
clone = deepcopy(data)
clone[0]["count"] += 1
print(data[0]["count"])Show answer
The output is 1. The dictionary inside the list is copied as part of the deep copy, so changing clone does not affect data.
Find the Bug
This code tries to duplicate a recipe book before editing the copy. It looks correct at first glance, but one change still leaks back to the original. Find the bug.
from copy import copy
recipes = {
"breakfast": ["eggs", "toast"],
"lunch": ["soup"]
}
draft = copy(recipes)
draft["breakfast"].append("fruit")
print(recipes)
print(draft)Show answer
The bug is that copy() makes only a shallow copy of the dictionary. The lists stored under the keys are still shared, so editing draft["breakfast"] also edits recipes["breakfast"].
Fixed code:
from copy import deepcopy
recipes = {
"breakfast": ["eggs", "toast"],
"lunch": ["soup"]
}
draft = deepcopy(recipes)
draft["breakfast"].append("fruit")
print(recipes)
print(draft)The fixed version works because deepcopy() duplicates the nested lists too.
When to Choose Each One
Pick the lightest option that still protects your data.
| If your data is... | Use this | Reason |
|---|---|---|
| Flat and simple | Shallow copy | New container is enough |
| Nested and mutable | Deep copy | Inner objects must not be shared |
| Immutable, like a tuple of strings | Usually no copy | Sharing is safe |
| Large and performance-sensitive | Shallow copy if possible | Deep copy can be expensive |
A deep copy is not automatically better. It solves shared-mutation bugs, but it also uses more time and memory.
When shallow copy is the better choice
Use shallow copy when you need a separate top-level container but the inner objects are meant to stay shared. For example, a list of database record objects may be safe to reuse if you only want a new list of the same records.
When deep copy is the better choice
Use deep copy when you need to edit nested structures independently. Configuration templates, form drafts, and complex nested data structures are common cases.
When no copy is needed
If the object is immutable, such as a string, number, or tuple containing only immutable values, copying is usually unnecessary. Reusing the same object is safe because its contents cannot change.
Interview Questions
Why is assignment not a copy in Python?
Assignment binds a name to an existing object. It does not create a second object. If the object is mutable, changes through either name affect the same underlying data.
Why does a shallow copy still share nested objects?
Because shallow copy only duplicates the first level. It does not recursively clone the contents. The inner objects are still referenced from both containers.
When should you avoid deep copy?
Avoid deep copy when the structure is large and you do not need full independence. It can be slower and use more memory than needed. It can also behave unexpectedly with objects that manage external resources.
How do you copy a list in Python?
For a shallow copy, use list.copy(), slicing, or copy.copy(). For a deep copy, use copy.deepcopy().
Try It Yourself
Create a nested list, make one shallow copy and one deep copy, then change the nested list in the copied versions. Verify which original values change and which stay the same.
- Create a list that contains two inner lists.
- Make one shallow copy with copy.copy().
- Make one deep copy with copy.deepcopy().
- Append a value to the first inner list in each copy.
- Print the original list, the shallow copy, and the deep copy.
Expected output:
The original list should change after the shallow copy is edited, but not after the deep copy is edited.
Hint: Import both copy and deepcopy from the standard library copy module, and use the same nested structure for all three variables.
Show solution
from copy import copy, deepcopy
original = [[1], [2]]
shallow = copy(original)
deep = deepcopy(original)
shallow[0].append(10)
deep[0].append(20)
print(original)
print(shallow)
print(deep)
# Output:
# [[1, 10], [2]]
# [[1, 10], [2]]
# [[1, 20], [2]]Summary
- A shallow copy creates a new outer object but shares nested objects.
- A deep copy creates a new outer object and recursively copies nested objects.
- Assignment is not a copy; it only creates another name for the same object.
- Use shallow copy for flat or shared data and deep copy for nested data that must be independent.
- Deep copy is safer for nested mutation, but it costs more time and memory.
Next, study Python mutable and immutable objects so you can predict when copying matters and when it does not.