When learning Python, I find some difficulty in understanding about mutable and immutable objects.
Let’s me break it down in ELI5 style.
Mutable Objects
What is mutable objects: Can be changed after creation. Updates happen in place, same memory reference.
Examples: list
, dict
, set
Analogy 1 – Blackboard
Like a blackboard in a our classroom: you can erase, rewrite, and modify the content. The board itself doesn’t change, only what’s written on it.
Board == List
Content in board == List items
Analogy 2 – Chicken gravy in a pot
In the pot, you can add water, salt, or more chicken (if you're hungry). It’s still more or less the same gravy, just modified.
Pot == Set
Chicken gravy == Set items
Immutable Objects
What is immutable objects: Cannot be changed once created. Any modification creates a new object in memory.
Examples: int
, float
, str
, tuple
, frozenset
Analogy 1 – Exam Question Paper
Once the exam question paper is printed, you can’t change it. If there’s a mistake, you need to print a new one (or provide grace marks).
Analogy 2 – Idli
Once steamed, an idli can’t be reshaped or unsalted. If you want a idli with less salt, you must make a new batch.
only immutable objects are hashable
Final takeaways
Understanding this helps you avoid bugs (like using mutable default arguments in functions).
Analogies are for fun. Peace.
Top comments (0)