Immutability: Everything in python is an object, once we create an object we cannot perform any changes in that object and if we are trying to implement any changes, then with those changes a new object will be created this process is called as immutability or Non-changeable behavior of an object is called as immutability.
Let us consider an example where
x=10, everything in python is an object, so here 10 is an object and x is the reference variable of that object, and for every object, the address will be there, so to print that address of an object we need
If I change the content of the x as
x=x+1, that x is an object when we are trying to make changes to the object then a new object will be created, and hence x will be pointing to that new object, so if you
print(id(x)) then the address of the new object is going print
And ten will not have any reference as x pointing to the new object so that it will be moved to the garbage collector
Let us consider another one example,
y=x so here x and y both are pointing to 10 only, you can check this practically
x=10 y=x print(id(x))=? print(id(y))=?
If I change the content of y,
y=y+1 and then a new object will be created and hence now onwards y is pointing to the new address of the new object.
x=10 y=y+1 print(x) print(y) print(id(x)) print(id(y))
Let us see why we need immutability by using the following example
c=10, here three reference variable are going to point to the same object because in python if we are trying to create an object with the same content again, it will check whether that object is already present or not if it is already present then it is going to use the same object again and hence a,b,c three variables are going to point to the same object, this process is called object reusability.
To check this practice, we can print the id of all the three reference variables
a=10 b=10 c=10 print(id(a)) print(id(b)) print(id(c))
b=10.234so here only one object has been created, and both a and b are pointing to the same object.
a=10.234 b=10.234 print(a is b)
a=True b=True print(a is b) a=False b=False print(a is b)
a="dhan" b="dhan" print(a is b)