Advertisements
Advertisements
प्रश्न
Prove with the help of an example that the variable is rebuilt in case of immutable data types.
Advertisements
उत्तर
When a variable is assigned to the immutable data type, the value of the variable cannot be changed in place. Therefore, if we assign any other value to the variable, the interpreter creates a new memory location for that value and then points the variable to the new memory location. This is the same process in which we create a new variable. Thus, it can be said that the variable is rebuilt in case of immutable data types on every assignment.
Program to represent the same:
#Define a variable with immutable datatypes as value
var = 50
#Checking the memory location of the variable
print("Before: ",id(var))
#Assign any other value
var = 51
#Checking the memory location of the variable
print("After: ",id(var))
OUTPUT:
Before: 10916064
After: 10916096
It can be seen that the memory location a variable is pointing at after the assignment is different. The variable is entirely new and it can be said that the variable is rebuilt.
