Take a look at this:
>>> a = 1
>>> b = 1
>>> print(a is b)
True
>>> c = 1.2
>>> d = 1.2
>>> print(c is d)
False
>>> hex(id(a))
'0x77fb6c20'
>>> hex(id(b))
'0x77fb6c20'
>>> hex(id(c))
'0x2185c8e1990'
>>> hex(id(d))
'0x2185c8e1a38'
>>> a = 900
>>> b = 900
>>> print(a is b)
False
>>> hex(id(a))
'0x2185d434e10'
>>> hex(id(b))
'0x2185d434eb0'
>>>
As you can see here when a
and b
are 1
, the memory location of the variables is same as they are cached by the python runtime. c
and d
are referred at different memory locations due to their data type being float. When we take a large value for a
and b
, their memory location is different.
is
statement in python isn't a comparison operator but tells if the variables referred are bound to the same objects.
As per here:
The current implementation keeps an array of integer objects for all
integers between -5 and 256, when you create an int in that range you
actually just get back a reference to the existing object. So it
should be possible to change the value of 1. I suspect the behaviour
of Python in this case is undefined. :-)