Understanding Mutable and Immutable Objects in Python


Ever wondered why sometimes your variable’s value changes instantly, while other times it creates something entirely new?
This is because in Python, everything is an object, and variables are simply references (or pointers) to these objects in memory.
Let’s break down one of the most important concepts in Python: mutable vs immutable objects.
🔹 What Does “Immutable” Mean?
Immutable objects can’t be changed after they are created.
Examples: str
, int
, tuple
When you try to "change" an immutable object’s value, Python actually creates a new object in memory and makes the variable point to it.
Example:
pythonusername = "Avni"
# 'username' points to the string "Avni"
username = "Avni Singh"
# Now 'username' points to a NEW string object "Avni Singh"
The original "Avni"
string is still in memory, but since no variable references it anymore, Python's garbage collector will eventually remove it.
📌 Key takeaway — You don’t actually modify immutable objects. You create new ones and reassign references.
🔹 What About Mutable Objects?
Mutable objects can be changed in place without creating a new object.
Examples: list
, dict
, set
pythonfruits = ["apple", "banana"]
fruits.append("mango")
print(fruits) # ['apple', 'banana', 'mango']
Here, the memory address of fruits
remains the same, but the contents are modified.
🔹 Why Does This Matter?
Understanding mutability helps you:
Avoid unexpected side effects when passing variables to functions
Predict performance and memory usage
Write cleaner and bug-free code
💡 Did you know? If two variables point to the same mutable object and you modify it via one variable, the change is visible to the other, because both variables point to the same memory location.
🚀 Conclusion
Mutable and immutable concepts are fundamental to mastering Python. Once you understand how they work, you’ll have better control over data flow, variable behavior, and memory efficiency in your programs.
✅ Next Step Idea for Readers:
In the next blog, we can explore how Python handles variable assignment and object IDs to visualize mutability.
Subscribe to my newsletter
Read articles from Avni Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by
