-1

I'm playing with the 'is' operator in the interactive shell when I encountered an odd behavior with the below code:

It goes as expected at first:

>>> x = 11

>>> y = 11

>>> x is y

True

But when I tried this one:

>>> x = 987456

>>> y = 987456

>>> x is y

False

After further tries using id() function, I noticed that integers >256 points on the same object while others are not. I also noticed that this behavior only occurs in the python interactive shell. What's with this behavior?

1 Answers1

-1

is checks for memory address. Immutable objects that are wrappers around C type tends to have same memory address, whereas others don't. The difference here is the bytes required to store the integers.

hspandher
  • 15,934
  • 2
  • 32
  • 45
  • 5
    This isn't a full answer, since you also need to explain why the memory address may be the same for small integers, but not for large ones. However, this is a duplicate so user can look up previous answers. – jpp Feb 27 '18 at 10:47
  • 3
    I cannot find a single trace of `==` in the question. – Sohaib Farooqi Feb 27 '18 at 10:48
  • The behaviour of `is` is an optimisation issue, not to do with wrappers around `C` types. – Peter Wood Jun 19 '18 at 08:55