Mutable vs Immutable Types in Python
Data Types Satellite
Mutable vs Immutable
Every Python object is either mutable (can change in place) or immutable (new object on change). Knowing which is which prevents hard-to-debug bugs.
Comparison
| Immutable | Mutable |
|---|---|
int, float, bool, str, tuple, frozenset | list, dict, set, bytearray |
- Reassigning an immutable object creates a new object:
name = "Ada"
name += " Lovelace" # new string allocated
- Mutating a mutable object changes it in place:
users = ["ada"]
alias = users
users.append("guido")
# alias also sees new element
Why it matters
- Function arguments: Mutating a list or dict inside a function affects the caller unless you copy it.
- Dictionary keys / set members: Must be immutable so hashes stay consistent.
- Thread safety: Immutable objects are inherently thread-safe; mutable objects need coordination.
Strategies
- Use
.copy()orcopy.deepcopy()for mutable structures when needed. - Prefer tuples/dataclasses with
frozen=Truefor read-only records.