Python Variable

Variable Assignment:

n = 300 — python creates an object of type integer in memory and assigns n as a pointer to it’s location.
m = n — python DOES NOT create a not integer object, but assigns m as a pointer to the same location.
n = “hello” — n no longer points to the location of 300 but now points to the location of the string object; m — continues to point to the location of 300
m = 40.3 — m now points to the location of the float type object; 300 is orphaned and there is no access to it.

Note: the id() method can show you the memory location of the object

Something interesting:
In [55]: n=300

In [56]: m=300

In [57]: id(n)
Out[57]: 4395607760

In [58]: id(m)
Out[58]: 4397257296
***variables point to object in different object locations


In [51]: n=30

In [52]: m=30

In [53]: id(n)
Out[53]: 4304949184

In [54]: id(m)
Out[54]: 4304949184
**Both variables point to the SAME object location

Here, m and n are separately assigned to integer objects having value 30. But in this case, id(m) and id(n) are identical!

For purposes of optimization, the interpreter creates objects for the integers in the range [-5, 256] at startup, and then reuses them during program execution. Thus, when you assign separate variables to an integer value in this range, they will actually reference the same object.