Data Structures14 min read
Mutability Explained
Understand the #1 beginner confusion: why some structures change in place and others don’t, and how this affects copying, functions, and bugs.
David Miller
December 14, 2025
2.0k56
Mutability means: can this object change after creation?
Mutable structures
- list
- dict
- set
- most class objects
Immutable structures
- tuple
- string
- int, float, bool
Why it matters
Because it affects:
- copying
- passing to functions
- unexpected bugs
Example: mutable reference bug
a = [1, 2]
b = a
b.append(3)
print(a) # [1, 2, 3]
Fix: copy
a = [1, 2]
b = a.copy()
b.append(3)
print(a) # [1, 2]
Example: immutable is safe
x = "cat"
y = x
y = "bat"
print(x) # cat
Graph: reference vs copy
flowchart LR
A[a] --> C[Same list object]
B[b] --> C
D[a.copy()] --> E[New list object]
Remember
- Most “surprising” bugs come from mutability
- Use copy() when needed
- Immutable data prevents accidental changes
#Python#Beginner#Core Skills