Variables under the hood in Python
In simple terms, variables are names attached to particular objects in Python. To create a variable, you just need to assign a value and then start using it. The assignment is done with a single equals sign (=):
From the above program it can be clarified that “age is assigned a value of 20” and “id no is assigned a value of 4067613”. Now age and id_no can be used in a statement or expression, and its value will be substituted.
In python variables are dynamic i.e The type of variable is known at the run time and also a variable may be assigned a value of one type and then later re-assigned a value of a different type.
What is actually happening when you make a variable assignment in Python?
Python is an object-oriented language. Any data item in a Python program is an object of a certain type or class like integer, float, string, etc.
From the above variable example when we are assigning value 20 to variable age the interpreter does the following:
- Creates an integer object
- Gives it the value 20
- Displays it to the console
Actually python variable is a symbolic name that is a reference or pointer to an object. When an object is assigned to a variable, the reference of the object can be used by its name, the data is also stored within the object itself.
Multiple object reference:
It refers to referencing an object to a previously assigned object.
Let’s have a look at this code below:
Here, Python does not create another object. It simply creates a new symbolic name or reference, new_age which points to the same object that was previously assigned.
If we change the value of new_age for example new_age=30, then Python creates a new integer object with the value 30, and new_age becomes a reference to it.
If we change the value of the above variable age=25, then new integer object with value 25 is created and age is referenced to it. Now the integer object that has 20 in it has been orphaned or lost the reference. There is no way to access it. If there is at-least a single reference to the object then it can be alive. When the number of references to an object drops to zero python will eventually notice that it is inaccessible and reclaim the allocated memory so it can be used for something else. This is how garbage collection is done in Python.
Note: For more information, refer Garbage Collection in Python