English

Prove with the help of an example that the variable is rebuilt in case of immutable data types.

Advertisements
Advertisements

Question

Prove with the help of an example that the variable is rebuilt in case of immutable data types.

Answer in Brief
Advertisements

Solution

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.

shaalaa.com
Concepts of Tuples in Python
  Is there an error in this question or solution?
Chapter 10: Tuples and Dictionaries - Exercise [Page 224]

APPEARS IN

NCERT Computer Science [English] Class 11
Chapter 10 Tuples and Dictionaries
Exercise | Q 7. | Page 224
Share
Notifications

Englishहिंदीमराठी


      Forgot password?
Use app×