The nature of Python is different from that of languages like C, where a variable is more-or-less a memory location.
In Python, a variable assignment can be thought of assigning a label to an object. Objects that have no labels referencing them are eventually reclaimed by the garbage collector. Multiple labels can point to the same object.
Look at the following:
In [1]: a = 1
In [2]: b = 1
In [3]: id(a), id(b)
Out[3]: (34377130320, 34377130320)
Both a
and b
reference the same object.
Note that in Python some type of objects (like numbers and strings) are immutable. You cannot change their instances. See:
In [4]: a += 1
In [5]: id(a)
Out[5]: 34377130352
After incementing, a
points to a different object.
As an aside, when CPython starts, it creates objects for often-used small integers (like 0-100). These objects are significantly bigger than what you would normally associate with an integer. Also note that using memory addresses as id
is a CPython implementation detail. So in CPython we can do:
In [6]: id(2) - id(1)
Out[6]: 32
In [7]: (id(100) - id(0))/32
Out[7]: 100.0
So in this case (64-bit FreeBSD OS, CPython 3.6) an integer object is 32 bytes.