What is Immutability in Python?
It means, after the creation of the object, we can’t perform any changes to it. If we try to make any changes, then a new object will be assigned to that reference variable.
x = 10 x = 11 // A new int object is created whose value is 11
In the first line, we are created an int object and assigned it a variable name ‘x’.
In the second line, we changed the value of x. Now x is holding the value 11. Internally, Python will not change the int object which was holding value 10. Instead, it will create a new int object and assign it to variable name x.
Python Data Types that support Immutability
In Python, Fundamental data types like int, string, float, and bool support Immutability.
Also Read – Square root c++ – sqrt() function with custom implementation
Why Immutability is required?
Let’s understand it with an example.
- Suppose, we are creating a program to record the Age of every citizen in the city.
- To create this program, we are assigning each individual citizen’s age inside an int variable. You will agree with the fact that there will be a lot of people inside a city whose age is same. E.g. There will be a lot of people whose exact age is 18.
- So, it would make a sense to assign all those people the same object with different reference variable names. It will drastically improve the memory utilisation of the code.
- Python does the exact same thing internally. It will create only One object for all the people whose having the same exact age and it will only assign the references to the object.
Advantages of Immutability in Python
- Improves memory Utilisation and it uses the memory efficiently
- Improves the performance. Immutable objects are generally quicker to access.
Checking for each value in memory? Won’t it decrease the performance?
In any programming language, object creation is the most expensive task. It is non comparable in front of checking each value inside memory. Apart from this, immutable objects are quicker to access. That’s why there is no issue in checking them again and again inside the program.
is Operator in Python
is operator is used in Python to check whether the objects are same or not. It will return true if the two references are sharing the same object and false if they are not sharing the same object.
x = 10 y = 10 z = 10 print(x is y) // prints true print(x is y is z) // prints true
I hope, you will find this article on Immutable Objects in Python useful. If you have any doubts or suggestions regarding this article then do comment below. I will try to answer it as soon as possible.
[…] Also Read – Immutability in Fundamental data types – Python 3 […]