Mutable and Immutable

Vishant SinghVishant Singh
2 min read

In the world of programming mutability is the ability of an object to be changed after it’s creation, on the other hand immutability is the inability to change of an object after it's creation. In simple words we can say that objects which have the nature of changeability is known as mutable objects while the objects which can’t be change once the object created is known as immutable objects.

Mutability and Immutability in Python

When we talk about the mutability and immutability in python then the scenario is little bit different don‘t worry upper discussed definition is true but in python mutability and immutability concept work with the reference of the object. “Once a object is created in memory with a location then if it is changeable means that it is mutable else immutable”.

This image can be little bit confusing for young developer of python in this image username changed “Tiger” to “Cat” DO you know why? If you know than congrats right now you have the knowledge of mutability and immutability in python and if your answer is "No” then try to know. In this example we assigning the value to username firstly “Tiger”, and then “Cat” with different memory location/reference, by which we are getting changed result “Tiger” to “Cat” but we did not changed the object we just changed the reference of user name.

In this image you can clearly see that firstly username pointed “Tiger” and then it pointed “Cat”, here we just change the reference “Tiger” to “Cat” but when we talk about mutable and immutable it means we are talking about change within the objects. In this case if we Change “Tiger” to “Cat” with same memory location then we can say that it is mutable otherwise it is immutable. But there is no change within the objects in this example so it is an immutable.

1
Subscribe to my newsletter

Read articles from Vishant Singh directly inside your inbox. Subscribe to the newsletter, and don't miss out.

Written by

Vishant Singh
Vishant Singh