Mutable and Immutable Objects

Elmustapha Abourar
3 min readMay 27, 2022

Hello everybody! Curious to know about mutability and immutability. Let’s do a check!

Mutable Object:

A mutable object is a changeable object that can be modified after its creation. Let’s take a look at an example.

Did you notice something?

There are two things ?

The list and its id before and after the modification of the list. The list in these two cases is different, but the id of the list is the same.

The question now is: What exactly is this id?

It is the object’s location in the memory and is unique to the Python Implementation.

Let’s see it in a practical way:

Starting from there, you can see that ids exist in the lists and in all objects.

Immutable Object:

An immutable object is an object whose state can never be modified after it is created.

Same variable has several id ? Here, the id is an integer that corresponds to the memory location where a value is stored.

Remember that 6 is stored at 139949231669648 and, after being changed to 7 the memory location is not the same.

Therefore, 7 is created in a different memory location because the variable a is immutable.

List of Mutable and Immutable objects :

Mutable objects: list, dict, set, byte array

Immutable objects: int, float, complex, string, tuple, frozen set, bytes.

So, now what have we learned is :

  • Python handles mutable and immutable objects in different ways.
  • Mutable objects are of great use in scenarios where there is a need to change the object size (e.g., list, set, and so on…).
  • Immutable objects’s are used when you want an object you created to always stay the same as it was when created.

“Immutable objects are accessible in a quicker way than mutable objects.”

“Changing Immutable objects is fundamentally expensive as it involves creating a copy; but, changing mutable objects is considered cheap.”

Sources :

Mutable vs Immutable Objects in Python — A Visual and Hands-On Guide (freecodecamp.org)

python — Immutable vs Mutable types — Stack Overflow

Mutable Objects vs Immutable Objects in Python — Real Python

--

--

Elmustapha Abourar

Software Engineer Student @Holberton School & Pro Dancers Choreographer DeeJay / Beat Maker