Menu

1 / 2

Understanding Mutable and Immutable Objects in Python

DEV Community·Samiksha Srivastav·6 months ago
#5vfOOdZz
Reading 0:00
15s threshold

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…

Continue reading — create a free account

Join HashtagPLUS to read full articles, follow hashtags, vote, and join the conversation.