Python Mutable or immutable object

What does mutable object and immutable object mean in Python? .When an object is created and stores certain value does the value stored by the object changes later on in the program or does it not changes at all.Those objects which retain their value through out it’s lifetime are known as immutable object.And those object which changes their value is known as mutable objects.Consider a code below.

>>> new=89
>>> new
>>> new=123
>>> new 

Look at the code and answer,has the value of ‘new’ object changed? you might say yes because at first we have assigned ‘new’ with 89 and after that we have assigned 123 so ‘new’ has changed it value from 89 to 123.

Well no! integer are immutable object,then you may ask why did ‘new’ give us 123 instead of 89? .Here is the concept,when we type ‘new=89’ an object was created to store the 89 value but when we assigned 123 to ‘new’ another object is created to store the value 123.This means two objects now exist,one that stores 89 and the other stores 123,the name ‘new’ is just used to access the objects,the original object that stores 89 is not altered in any way it is still their.Consider the code below.

>>> new=89
>>> id(new)
>>> new=123
>>> id(new)

Note the ‘id()’ function returns a unique value for each objects,different unique ‘id’ shows different objects.

Well the above code returns a unique ‘id’ for the first object that stores 89 and another different ‘id’ for object that stores 123.Bear in mind objects that store integer are immutable.

Mutable object example

Let us take another example of object ‘New’ of class type ‘Hair’.(It might too early to introduce the concept of ‘class’ here but it’s just for the sake of an example).We will try to make a class name ‘Hair’ with the property ‘cost’ ,the code is given below.

>>> class Hair:
        def __init__ (Style,cost)

>>> New=Hair(10) #10 is assigned to cost
>>> New.cost #get the value of 'cost'
>>> id(cost) #get the 'id' of 'cost'
>>> New.cost=190 #change the value of 'cost'
>>> New.cost
>>> id(cost)

First we assigned 10 to ‘cost’ and we check the id of ‘New’ which we got as ‘92159568’.We changed the value of ‘cost’ to 190 and we check teh id of ‘New’ again,which is still 92159568.This means the object ‘New’ is mutable because we could change the value of ‘cost’ but the id of ‘New’ still remains the same.

Note every custom object is mutable unless you make it immutable

Leave a Reply

Your email address will not be published. Required fields are marked *