Understanding Dynamic Variable Allocation in Python

I was always curious about how Python assigns values under the hood to the same variable.
Example
Let's say we declare:
a = 2
print(type(a)) # This will give INT as a response
a = 2
a = "Hello World"
print(type(a)) # This will give String as a response
This is where the interest pops up that a was initially an INT but suddenly converted to a String.
How it works
It uses objects when assigning values to variables and it does it at runtime.
When we say
a = 2:At runtime, it creates an object of
INTand assigns the value of2to that object.It increments the reference count by 1.
It assigns the reference of that object to the
avariable.
When we reassign
"Hello World"(a string value) toa:In the background, it creates another object of
Stringwith the value"Hello World"assigned to it.It increments the reference of the new object's count by 1.
The reference of this newly created object is assigned to the
avariable.The reference count for the
INTobject decreases by 1.
When the reference count of an object hits 0, it becomes eligible for garbage collection. At runtime, the Python garbage collector collects the INT object as it doesn't have any references and the reference count is set to 0.


