Mutable vs Immutable Objects — Deep Dive with Real Bugs
Introduction — Why Mutable vs Immutable Still Causes Production Bugs
Mutable vs immutable objects sound like a basic Python topic.
Yet in real codebases, this concept still causes silent bugs, unexpected behavior, and extremely confusing issues even for experienced developers.
The problem is rarely about definitions.
It is about forgetting how Python handles object references behind the scenes.
This article stays practical, avoids theory overload, and focuses on real bugs that show up in production.
Meaning of Mutability in Python (With Common Types)
In Python, variables do not store values. They store references to objects in memory.
Mutability means whether an object can be changed after it is created.
Immutable objects
- Cannot be modified in place
- Any change creates a new object
- Safer to share across code
Common immutable types
- int
- float
- str
- tuple
- frozenset
Mutable objects
- Can be modified in place
- Changes affect all references to the object
Common mutable types
- list
- dict
- set
- bytearray
Key idea to remember
- Assignment never copies objects
- It only copies references
Real Bug 1 — Mutable Default Arguments
This is one of the most common and dangerous Python bugs.
def add_item(item, items=[]):
items.append(item)
return items
print(add_item(1))
print(add_item(2))
# Expected output
[1]
[2]
# Actual output
[1]
[1, 2]Why this happens
- Default arguments are evaluated once
- The same list is reused across function calls
How to fix it
- Use None as the default
- Create a new list inside the function
def add_item(item, items=None):
if items is None:
items = []
items.append(item)
return items
Real Bug 2 — Shared References and Accidental State Changes
This bug happens when multiple variables point to the same mutable object.
a = [1, 2, 3]
b = a
b.append(4)
print(a)
Why this is dangerous
- b is not a copy of a
- Both point to the same list in memory
- This becomes critical in
- Configuration objects
- Cached data
- Shared state in services
- Safer alternatives
- Use copy() or slicing
- Use immutable data where possible
b = a.copy()Real Bug 3 — Modifying Data Inside Functions Without Expectation
Functions can silently mutate objects passed to them.
def process(data):
data.append(99)
numbers = [1, 2, 3]
process(numbers)
print(numbers)Why this is dangerous
- The caller may not expect mutation
- Side effects make code harder to reason about
Better patterns
- Return new objects instead of mutating
- Clearly document functions that mutate inputs
def process(data):
return data + [99]When Immutability Matters — Hashing, Dict Keys, and Sets
Immutable objects can be hashed. Mutable objects cannot.
Get Code With Ahmad’s stories in your inbox
Join Medium for free to get updates from this writer.
That is why
- Lists cannot be dictionary keys
- Tuples can be dictionary keys (if they contain only immutable items)
my_dict = {(1, 2): "valid"}Why this matters
- Hashing relies on objects never changing
- Mutating a hashable object would break dictionaries and sets
Practical Rules to Avoid Mutable vs Immutable Bugs
Keep these rules in mind
- Never use mutable default arguments
- Assume function arguments can be mutated unless proven otherwise
- Prefer immutable data for shared state
- Copy mutable objects when passing across boundaries
- Make side effects explicit
Written by Ahmad — sharing practical Python and software engineering insights at Medium: @CodeWithAhmad








