5.9 Mutable vs Immutable Types
The difference between mutable and immutable objects in Python, which built-in types fall into each category, and how identity (id()) behaves differently for each.
Definition
What Is It?
A MUTABLE object’s value can be changed in place after creation (its id stays the same); an IMMUTABLE object’s value can never change — any “modification” actually creates a brand-new object.
Why Does It Matter?
This affects correctness (shared references to mutable objects can surprise you), safety (immutable objects are safe to share across threads), and what can be used as a dict key.
Mutating a mutable object keeps its identity; “mutating” an immutable one creates a new object.
Examples
| Mutable | Immutable |
|---|---|
list | tuple |
dict | str |
set | int, float, bool, complex |
bytearray | bytes, frozenset |
Memory Behavior
How Is It Used?
Mutating a list in place leaves its identity (id) unchanged; reassigning a tuple’s contents is impossible, so any “change” produces a new object with a new id:
>>> l = [1, 2, 3]
>>> id(l)
140420020687424
>>> l.append(4) # in-place mutation
>>> id(l) # SAME id -- same object, modified
140420020687424
Comparison Table
| Property | Mutable | Immutable |
|---|---|---|
| Can change after creation? | Yes | No |
| Safe to use as dict key? | No (unhashable) | Yes (if hashable) |
| Safe to share across threads? | Requires care | Inherently safe |
id() after modification | Unchanged | N/A — new object created |
Quick Interview Answer
“A mutable object’s value can change in place — its
idstays the same after modification, like alist.append(). An immutable object’s value can never change — any apparent ‘modification’ actually builds a brand-new object with a newid, liketuple + (3,). This is why only immutable, hashable types can be used as dict keys or set members, and why immutable objects are inherently safer to share across threads.”
Common Mistakes
- Assuming
tuple + (x,)modifies the tuple in place — it creates and returns an entirely new tuple; the original is untouched. - Sharing a mutable default or a mutable object across function calls without realizing all references point to the same underlying object.
- Trying to use a
listordictas a dict key, hittingTypeError: unhashable type, instead of reaching for the immutable equivalent (tuple, frozen structure).
Add More Questions to This Guide
Know a question that should be here? Share it and help the community!
Open Google Form