1

I was working with DataStructures Lab. and I found out that:

a = 2
b = 2
print(id(a)) #1632496144
print(id(b)) #1632496144

Both a and b variables have same id but, when I did this

x = 500
y = 500
print(id(x),id(y))

it's written here that if the range will exceed from -3 to 256, it will give different memory locations.

My question is that why these IDE's are giving different results?

In JUPYTER NOTEBOOK the output is this: 2999875658288 2999875658256 different memory locations

while In VS CODE the output is this:

1495642916912 1495642916912 same memory locations

Midha Tahir
  • 128
  • 2
  • 8

1 Answers1

1

Python (CPython, actually) caches some small, frequently used values like these in a cache so it does not has to create and destroy these objects all the time.

Here is a short description about this on the C API reference.

Also, sometimes Python will do the same for strings and other objects, so for example you can do the same with the string "a" like this: print(id("a"), id("a")) and you get the result 140301498960896 140301498960896.

Keep in mind that CPython does not guarantee this behavior, this is just an implementation detail and it is not part of the language design itself.

Under Jupyter if I run the following cell: id(500), id(500), I get (139638184229584, 139638184229584) but if I run the same in the next line, that will return a different pair of numbers (the values are still the same, though). Jupyter is probably keeping these values alive and that is causing this behavior.

I think CPython keeps objects in small data cache below 256 bytes, but I'm not sure about this number not I could find a reference for it. If I find a reference, I will edit my answer.