1

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?

Rheatey Bash
  • 779
  • 6
  • 17
  • The cause of this is internal optimization in the CPython interpreter. It is nothing you should rely on in code. – Klaus D. May 10 '19 at 10:26

2 Answers2

5

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.

Chandella07
  • 2,089
  • 14
  • 22
  • Can you please provide any reference to this? – Rheatey Bash May 10 '19 at 10:22
  • This is for python3, In CPython, the C-API function that handles creating a new int object is `PyLong_FromLong(long v)`. see the documentation on https://docs.python.org/3.6/c-api/long.html – Chandella07 May 10 '19 at 10:25
-1

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
user3340459
  • 435
  • 5
  • 13
  • This doesn't explain why the id stays the same every time he assigns `a = -5` but changes every time he assigns `a = -6`. – T Burgis May 10 '19 at 10:18