Welcome to Day 30 of the 100 Days of Python series!
You’ve made it to the one-third milestone! 🎉
Today, we’ll tackle an important concept that confuses many Python learners:
Copying vs Cloning Lists — Shallow vs Deep Copy.
Understanding the difference between these is crucial for working with complex data structures.
🎯 What You'll Learn
- The difference between assignment, shallow copy, and deep copy
- How list copying really works in memory
- Practical examples and common pitfalls
- When to use shallow vs deep copy
📦 Assignment Is NOT Copying
Let’s start with a basic truth:
a = [1, 2, 3]
b = a
You might think b
is a new copy, but it’s just another reference to the same list.
b.append(4)
print(a) # Output: [1, 2, 3, 4]
Why? Because both a
and b
point to the same object in memory.
✂️ How to Actually Copy a List
There are a few ways to make a real copy of a list:
✅ 1. Using list()
a = [1, 2, 3]
b = list(a)
✅ 2. Using Slicing
a = [1, 2, 3]
b = a[:]
✅ 3. Using .copy()
a = [1, 2, 3]
b = a.copy()
All of the above create a shallow copy.
🌊 Shallow Copy: What It Means
A shallow copy copies the outer list, but not the nested objects inside.
🔁 Example:
a = [[1, 2], [3, 4]]
b = a.copy()
b[0][0] = 999
print(a) # Output: [[999, 2], [3, 4]]
Even though b
was a copy of a
, changing b[0][0]
also changed a[0][0]
.
➡️ Why? Because both a[0]
and b[0]
point to the same inner list.
🧬 Deep Copy: Full Separation
To avoid shared references, use deep copy with the copy
module:
✅ Example with copy.deepcopy()
:
import copy
a = [[1, 2], [3, 4]]
b = copy.deepcopy(a)
b[0][0] = 999
print(a) # Output: [[1, 2], [3, 4]]
print(b) # Output: [[999, 2], [3, 4]]
Now a
and b
are completely independent, even at nested levels.
🔍 When to Use What
Situation | Use This |
---|---|
Simple list of numbers | Shallow copy ([:] ) is fine |
Nested lists or complex objects | Use copy.deepcopy()
|
Only need a reference (no cloning) | Use assignment (= ) |
🧪 Real-World Analogy
Think of:
-
Assignment (
=
) as giving someone your house key - Shallow copy as duplicating rooms, but sharing furniture
- Deep copy as building a whole new house with new furniture
💡 Common Mistakes
-
Assuming
.copy()
also clones nested lists — it doesn’t. - Modifying one nested list and being surprised the original changes.
-
Using
copy.deepcopy()
blindly — it’s slower and memory-heavy for large data, use it only when needed.
🧭 Recap
Today you learned:
✅ Assignment is just reference, not copying
✅ Shallow copy copies the outer object
✅ Deep copy duplicates everything recursively
✅ Use copy.deepcopy()
to avoid shared references