Codementor Events

The python integer and the 'is' operator

Published Feb 03, 2020

I came across this question when one of my friends asked me what happens to a python Integer when it is created. This would have a simple answer which is an address space would be allocated in the memory for the integer. The follow-up question made me write this post.
Do all the integers objects have the same behavior in python ?
The answer to this question is 'No'.


$ python
Python 3.6.9 (default, Oct 31 2019, 20:19:38)
Type "help", "copyright", "credits" or "license" for more information.
>>> a = 256
>>> b = 256
>>> a is b
True
>>> c = 257
>>> d = 257
>>> c is d
False
>>>

The is operator here checks if id() of two objects are same. id() is the address memory allocated to an object
So what we see here is that the integer 256 is referenced by the variables a and b is the same address space. However, when we are creating integer 257 both variables c and d are allocated different memory locations.

>>> print (id(a), id(b))
4402039920 4402039920
>>> print (id(c), id(d))
4406554384 4404964784

As we can see the memory referenced in the case of 256 is same memory address while that of 257 is different address space.
In python, this behavior can be seen in the integer range of [-5, 256]
So next time an interviewer asks this question, you know what the answer is.

Discover and read more posts from Srinaveen Desu
get started