0
a=543
b=543

print(id(a),id(b))
print(a is b)

I am a Python newbie and my understanding of the above code is that

  • a = 543 => Since 543 is not in the small integer cache range of -5 to 256, a new pyobject of type integer with value 543 is created and the name/label a is given to that pyobject
  • b = 543 => a new pyobject of type integer with value 543 is AGAIN created and the name/label b is given to that pyobject
  • Since a and b refer to two different objects, their identities are different and thus id(a)==id(b) must return False

Below is the snapshot of running the above code using Python interpreter in terminal. And the result is what I expected

run in python interpreter

But the same code when ran through VS Code is returning same id for both a and b and id(a)==id(b) as True

run in VS Code

Is my understanding that a different object is created every time incorrect?

  • If yes, why is it behaving that way with Python interpreter?

Or is just VSCode doing something that I don't understand yet?

learner
  • 21
  • 4
  • FWIW: stop caring about this. It's all internal optimisation, which is entirely irrelevant to any code you'll ever write, because thou shalt not care about the identity of integers, or most other objects in most cases, in actual code. – deceze Oct 19 '22 at 10:12
  • @deceze unhelpful & doesnt address why this is happening – DrBwts Oct 19 '22 at 10:13
  • 1
    @DrBwts I've picked out a duplicate above which explains what's happening. I just feel compelled to add this comment, since there seems to be a weird obsession with ids of integers, when it never matters in actual code. – deceze Oct 19 '22 at 10:14
  • @deceze, Thank you. So this is because of the optimization done at compilation stage (same literal when used multiple times is created only once). I checked in REPL with a=543; b=543 in same line. Since both assignments are compiled together, now bth ids are same! Thanks again – learner Oct 19 '22 at 10:42

0 Answers0