Understanding mutability is essential to avoid unexpected bugs and to truly grasp how Python manages memory efficiently.
📌 Mutability vs Immutability in Python (With Memory Behavior)
Before diving deep, remember one core idea:
Python variables are references to objects, not containers of values.
This single concept explains most confusion around mutability.
🔷 What Does Assignment Mean in Python?
In Python, variables do not store values directly.
A = 4
This means:
-
Arefers to an object with value4 - Python follows name → object reference, not value copying
🔷 Immutable Objects in Python
✅ Common Immutable Types
intfloatstrtupleboolfrozenset
Immutable objects cannot be modified after creation.
🔹 Example: Integer Immutability
A = 4
B = 4
Internal Behavior
- Python checks whether object
4already exists - If yes, both variables reference the same object
- This is safe because integers are immutable
A ──► 4 ◄── B
🔷 Reassigning an Immutable Object
B = 5
What Python Does
- It does not change object
4 - It creates a new object
5 -
Bnow references5 -
Aremains unchanged
A ──► 4 B ──► 5
✔️ This prevents accidental side effects.
🔷 Proof Using id()
A = 4
B = 4
print(id(A), id(B)) # Same ID
B = 5
print(id(A), id(B)) # Different IDs
🔷 Mutable Objects in Python
⚠️ Common Mutable Types
listdictsetbytearray- user-defined objects (classes)
Mutable objects can be modified in place.
🔹 Example: Mutable List Behavior
A = [1, 2, 3]
B = A
Both A and B reference the same list:
A ──► [1, 2, 3] ◄── B
🔷 Modifying a Mutable Object
B.append(4)
print(A)
Output
[1, 2, 3, 4]
Reason
-
append()modifies the list in place - Both references see the change
🔷 How to Avoid Side Effects with Mutable Objects
✔️ Use Copying
A = [1, 2, 3]
B = A.copy() # or list(A)
B.append(4)
print(A) # [1, 2, 3]
Now A and B refer to different objects.
🔷 Comparison: Mutable vs Immutable
| Feature | Immutable | Mutable |
|---|---|---|
| Can modify object | ❌ No | ✅ Yes |
| New object on change | ✅ Yes | ❌ No |
| Shared references safe | ✅ Yes | ❌ Risky |
| Memory efficient | ✅ Yes | ❌ Sometimes |
| Examples | int, str, tuple | list, dict, set |
🔷 Why Python Uses Both
- Immutables → safety, predictability, performance
- Mutables → flexibility, efficiency for large data
Python balances performance + safety by supporting both.
⭐ Golden Rule
Python variables are references to objects.
Immutable objects create new memory on change;
Mutable objects modify existing memory.
🎯 Interview One-Liner
Python avoids side effects for immutable objects by rebinding names instead of modifying memory, while mutable objects require careful reference handling.
Top comments (0)