I initialised different values for different variables in python as
x = 10
y = 20
z = 30
when i use id(x)
, id(y)
, id(z)
for finding the respective address of x,y,z i found that all their address are differed by 320.
Why they are differed by 320 and why their address are not continuous.
Advertisement
Answer
You are seeing the results of a CPython optimisation called small integer cache.
CPython stores integers between -5 and 256 (inclusive) in a special cache as they are frequently used in user programs. This way the interpreter doesn’t have to initialise a new object every time you use a number:
>>> x = 10
>>> y = 10
>>> id(x) == id(y)
True
while
>>> x = 1000
>>> y = 1000
>>> id(x) == id(y)
False
Now, assume that the small integer cache looks like this in memory:
[-5, -4, -3, , 10, 20, , 256]
Small integers normally take 28 bytes in Python 3, but probably because of some 4 byte overhead, each number above takes up exactly 32 bytes:
>>> id(1) - id(0)
32
When you do
>>> x = 10
>>> y = 20
You actually assign memory locations of 10
and 20
in the small integer cache to the variables x
and y
, respectively. That’s why you are seeing a difference of 320 bytes (32 * 10) between them.
Note that this behaviour is only guaranteed for CPython. Other Python interpreters may not have a small integer cache, or they might implement the id()
function differently.