Skip to main content
Editor

Python Copy vs Deepcopy: Why Your "Copy" Isn't Really a Copy

Intermediate20 min5 exercises70 XP

Leer en españolЧитать на русскомLer em portuguêsอ่านภาษาไทย

0/5 exercises

Imagine you have a folder full of photos. You make a copy of the folder and give it to a friend. But here's the catch - only the folder is new. The photos inside are the same physical photos, shared by both folders. If your friend draws a mustache on one, your photo has the mustache too.

This is exactly how Python's default copying works. You think you made an independent copy, but the inner objects are still shared. It's one of the most confusing bugs in Python, and it trips up beginners and experienced developers alike.

In this tutorial, you'll learn the difference between assignment, shallow copy, and deep copy. By the end, you'll know exactly when to use each one and never get bitten by a "shared reference" bug again.

Why Does Changing a "Copy" Change the Original?

Let's start with the most common surprise. When you write b = a, you are NOT making a copy. You're creating a second name for the exact same object. Both a and b point to the same data in memory.

Assignment creates an alias, not a copy
a = [1, 2, 3]
b = a # NOT a copy - just a second name
b.append(4)
print(a) # [1, 2, 3, 4] - a changed too!
print(b) # [1, 2, 3, 4]
Output
[1, 2, 3, 4]
[1, 2, 3, 4]

This happens because a and b are two labels stuck on the same box. When you put something new in the box through label b, you see it when you look through label a too.

You can verify that two variables point to the same object using the is operator or by checking their id().

Checking object identity with is and id()
a = [1, 2, 3]
b = a
print(a is b) # True - same object
print(id(a)) # Same number...
print(id(b)) # ...as this one
Output
True
80036304
80036304

What Is a Shallow Copy?

A shallow copy creates a new outer container but does NOT copy the objects inside it. The new list is independent at the top level, but any nested objects are still shared with the original.

There are several ways to make a shallow copy of a list.

Three ways to shallow copy a list
original = [1, 2, 3]
# Three ways to shallow copy a list
copy1 = original.copy() # .copy() method
copy2 = original[:] # slice from start to end
copy3 = list(original) # list() constructor
# They are all independent copies
copy1.append(99)
print(original) # [1, 2, 3] - unchanged!
print(copy1) # [1, 2, 3, 99]
Output
[1, 2, 3]
[1, 2, 3, 99]

For dictionaries, use .copy() or dict().

Shallow copying a dictionary
original = {'name': 'Alice', 'age': 25}
copy1 = original.copy() # .copy() method
copy2 = dict(original) # dict() constructor
copy1['age'] = 30
print(original) # {'name': 'Alice', 'age': 25} - unchanged
print(copy1) # {'name': 'Alice', 'age': 30}
Output
{'name': 'Alice', 'age': 25}
{'name': 'Alice', 'age': 30}

This looks perfect. But here's the trap. Shallow copy only copies one level deep. If your list contains other lists (or dicts), those inner objects are still shared.

The shallow copy trap with nested data
# Shallow copy with nested data - the trap!
original = [[1, 2], [3, 4], [5, 6]]
shallow = original.copy()
# Modifying the outer list is fine
shallow.append([7, 8])
print(len(original)) # 3 - unaffected
print(len(shallow)) # 4 - only shallow changed
# But modifying an INNER list affects both!
shallow[0].append(99)
print(original[0]) # [1, 2, 99] - original changed too!
print(shallow[0]) # [1, 2, 99]
Output
3
4
[1, 2, 99]
[1, 2, 99]
Shallow copy: inner lists shared
original = [[1, 2], [3, 4]]
shallow = original.copy()
shallow[0].append(99)
print(original)  # [[1, 2, 99], [3, 4]]
Deep copy: everything independent
import copy
original = [[1, 2], [3, 4]]
deep = copy.deepcopy(original)
deep[0].append(99)
print(original)  # [[1, 2], [3, 4]]

What Is a Deep Copy and When Do You Need It?

A deep copy creates a completely independent clone. It copies the outer object AND recursively copies every mutable object inside it, no matter how deeply nested. The copy shares nothing you can change with the original: only values that can't change, like numbers and strings, are reused.

To make a deep copy, you need the copy module from Python's standard library.

Deep copy creates a fully independent clone
import copy
original = [[1, 2], [3, 4], [5, 6]]
deep = copy.deepcopy(original)
# Modify the deep copy
deep[0].append(99)
deep.append([7, 8])
print(original) # [[1, 2], [3, 4], [5, 6]] - completely unchanged!
print(deep) # [[1, 2, 99], [3, 4], [5, 6], [7, 8]]
Output
[[1, 2], [3, 4], [5, 6]]
[[1, 2, 99], [3, 4], [5, 6], [7, 8]]

Deep copy works with dictionaries too, including deeply nested structures.

Deep copy with nested dicts and lists
import copy
user = {
'name': 'Alice',
'scores': [90, 85, 92],
'profile': {'level': 5, 'badges': ['star', 'gold']},
}
clone = copy.deepcopy(user)
# Modify the clone at every level
clone['name'] = 'Bob'
clone['scores'].append(100)
clone['profile']['badges'].append('diamond')
print(user['name']) # Alice
print(user['scores']) # [90, 85, 92]
print(user['profile']['badges']) # ['star', 'gold']
print(clone['name']) # Bob
print(clone['scores']) # [90, 85, 92, 100]
print(clone['profile']['badges']) # ['star', 'gold', 'diamond']
Output
Alice
[90, 85, 92]
['star', 'gold']
Bob
[90, 85, 92, 100]
['star', 'gold', 'diamond']

Under the Hood: How Python References Work

To truly understand copying, you need to understand how Python stores data. Every piece of data lives somewhere in memory as an object. Variables are just names that reference (point to) those objects.

Assignment copies the reference. Shallow copy creates a new container with the same references inside. Deep copy creates a new container whose references point to new copies of every mutable object inside.

Visualizing references with is
import copy
inner = [1, 2, 3]
original = [inner, inner] # Both slots point to the same inner list
shallow = copy.copy(original)
deep = copy.deepcopy(original)
print(original[0] is original[1]) # True - same inner list
print(shallow[0] is original[0]) # True - shallow shares inner objects
print(deep[0] is original[0]) # False - deep made a new copy
Output
True
True
False

Here's a summary table of the three approaches.

Summary: assignment vs shallow vs deep copy
# Summary:
# ─────────────────────────────────────────────────────
# Method | New outer? | New inner? | Safe for nested?
# ─────────────────────────────────────────────────────
# b = a | No | No | No
# b = a.copy() | Yes | No | No
# b = deepcopy(a) | Yes | Yes | Yes
# ─────────────────────────────────────────────────────
print("Assignment: same outer, same inner")
print("Shallow copy: new outer, same inner")
print("Deep copy: new outer, new inner")
Output
Assignment:   same outer, same inner
Shallow copy: new outer, same inner
Deep copy:    new outer, new inner

When Should You Use Each Type of Copy?

Use assignment (b = a) when you intentionally want two names for the same data. This is common when passing data to functions - you usually want the function to work with the original.

Use shallow copy when you have a flat list or dictionary (no nested mutable objects) and need an independent copy. This covers most everyday cases.

Use deep copy when you have nested mutable objects (lists of lists, dicts with list values, etc.) and need a fully independent clone. This is essential when you want to modify the copy without any risk of affecting the original.


Practice Exercises

Predict the Output: Assignment Aliasing
Predict Output

Read the code carefully. What will it print? Remember that = with lists creates an alias, not a copy.

Type the exact output.

a = [10, 20, 30]
b = a
b[1] = 99
print(a)
print(a is b)
Make an Independent Copy
Fix the Bug

The code below tries to create a backup of the original list before modifying it. But the backup changes too! Fix the code so the backup stays unchanged.

Expected output:

Original: [1, 2, 3, 4]
Backup: [1, 2, 3]
original = [1, 2, 3]
backup = original
original.append(4)
print(f"Original: {original}")
print(f"Backup: {backup}")
Predict the Output: Shallow Copy Trap
Predict Output

This code uses a shallow copy on nested data. Read it carefully and predict what will be printed.

Type the exact output.

original = [[1, 2], [3, 4]]
shallow = original.copy()
shallow[0].append(5)
print(original)
print(shallow)
Safe Copy of Nested Data
Write Code

Create a fully independent copy of the original data using deep copy. Then add the score 100 to the copy's scores list. Print the original scores and the copy's scores on separate lines to prove they are independent.

original = {
'name': 'Alice',
'scores': [85, 90, 78],
}
# Create a deep copy
# Add 100 to the copy's scores
# Print original scores, then copy's scores
Fix the Game State Bug
Fix the Bug

This game saves a checkpoint of the player's state, then the player picks up an item. But when we load the checkpoint, the item is already there! Fix the code so the checkpoint is a truly independent snapshot.

Expected output:

Checkpoint inventory: ['sword', 'shield']
Current inventory: ['sword', 'shield', 'potion']
player = {
'name': 'Hero',
'hp': 100,
'inventory': ['sword', 'shield'],
}
# Save checkpoint
checkpoint = player.copy()
# Player picks up a potion
player['inventory'].append('potion')
print(f"Checkpoint inventory: {checkpoint['inventory']}")
print(f"Current inventory: {player['inventory']}")

Harder problems

More problems on this topic: Data structures

Related Tutorials

Was this tutorial helpful?