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

enter image description here

What could be the cause of this behavior?

2 Answers

4
Chandila07 On Best Solutions

Take a look at below example:

>>> a=256
>>> b=256
>>> print(id(a),id(b))
(31765012, 31765012)
>>> 
>>> c=257
>>> d=257
>>> print(id(c),id(d))
(44492764, 44471284)
>>> 

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.

-1
user3340459 On

From help(id):

id(obj, /) Return the identity of an object.
This is guaranteed to be unique among simultaneously existing objects. (CPython uses the object's memory address.)

For small numbers (not exactly sure how small), python only keeps one "version" of each number in memory. This is why every time you assign -5, you get the same memory location. When you assign -6, the address changes. If you try a larger number, you will get different results each time. Example:

>>> a = 9999999999999999999999; id(a)
140517821614080
>>> a = 9999999999999999999999; id(a)
140517821497216