DEV Community

Samiksha Srivastav
Samiksha Srivastav

Posted on

Understanding Mutable and Immutable Objects in Python

Now let's discuss mutable and immutable objects in Python.

First,

  • Mutable means something that can change
  • Immutable means something that cannot change

So, any data or object whose value can be changed after creation is called mutable, and those which cannot be changed are called immutable.

It's All About Memory
What does "change" actually mean here?

This concept is all about how values are stored in memory.

Let’s Take an Immutable Data Type (Integer)
Let’s understand this with an example in the Python shell:

But Wait…

We know that integers are immutable,
so how are we able to “change” the value of int_2?

What’s Actually Happening?
When we create int_1 = 5, a value 5 is stored in memory, and int_1 refers to it
When we assign int_2 = int_1, both variables refer to the same memory location (value 5)
But when we do int_2 = 8, we are not modifying 5

Instead, Python creates a new object (8) in memory,
and now int_2 starts referring to this new location

While int_1 still refers to the original value 5

Key Insight

Immutable objects cannot be changed in place.
Any “change” actually creates a new object in memory.

What About Mutable?

Mutable objects (like lists, dictionaries, etc.) can be changed directly without creating a new object.

Final Thought

So, mutable vs immutable is not just about “change” -
it’s about how Python handles memory and references internally.

If you’re learning Python, follow along - I’m sharing my journey step by step.

Top comments (0)