What is immutable in Python
The contents of some Python objects can be changed after they are created while others can’t be changed. Objects such as integer, float and complex number objects occupy the memory and memory contents can not be changed. Such objects are called immutable. Tuple, String and dictionary objects are also immutable.
Objects of these types can’t be modified once created. Suppose you have the following lines of code, which are executed in the order shown. You initialize two variables, a
and b
, to two different objects with values 1
and 2, respectively. Then you change the binding of the variable a
, to a different object with a value of 3
.
a = 1
b = 2
a = 3
- When you create the object with value
1
, you bind the object to the variable nameda
. - When you create the object with value
2
, you bind the object to the variable namedb
. - In the final line, you’re re-binding the variable named
a
to a completely new object, one whose value is3
.
The old object with a value of 1 may still exist in computer memory, but you lost the binding to it; you don’t have a variable name as a way to refer to it anymore.
Once an immutable object loses its variable handle, the Python interpreter could delete the object to reclaim the computer memory it took up, and use it for one thing else. In contrast to other programming languages, programmers doesn’t have to worry about deleting old objects. Python takes care of this through a process called “garbage collection”.