I have just came across a weird behavior while checking the id
of a variable assignment. I had run following code
a = -5
print(id(a))
and got id as follows
140710231913104
I get the same id
while executing Jupyter cell many times if a >= -5
whereas, if I assign and run a < -5
, I get different id
each time after executing the Jupyter cell. Find summary in below image
What could be the cause of this behavior?
Take a look at below example:
This will help you understand the unexpected behaviour for integers. Whenever you create a Int in range -5 to 256 you actually just get back a reference to the existing object. This is called Integer Caching in python.