0

I have stumbled upon a "feature" of Python, like so:

x = 256
x is 256   # returns True

x = 257
x is 257   # returns False

Integers in range [-5, 256] (inclusive) return True, while others return False.

I understand that the 'is' operator tests for the same reference, while the '==' operator tests for the same value. However, I don't understand the dark magics involved here, and Googling "Python is" doesn't help. Anyone have a nudge in the right direction?

My intuition is that the numbers that return True have permanent locations in memory - behind the scenes, Python is replacing both 'x' and '256' with a reference to that location. Less frequently used numbers do not, and are thus stored in whatever memory is available. But I wasn't a CS major, so I'm behind the curve on the "lower level" aspects of programming. (Working on it, however...)

Cedrus
  • 101
  • 2
    The short and the long of it: CPython caches small `ints`. This is an implementation detail. – juanpa.arrivillaga Apr 07 '17 at 03:18
  • 1
    Good intuition, though :). I'm not sure that a CS background would necessarily make this obvious, unless that CS education heavily features language design and implementation, and you happened to have focused on Python. – juanpa.arrivillaga Apr 07 '17 at 03:24
  • 1
    By the way, I would read [this](http://stackoverflow.com/a/34964030/5014455) answer, it is particularly good, and also answers why when you use any literal, `257 is 257` and `600 is 600` turn out to be `True` also! (hint, another, different optimization) – juanpa.arrivillaga Apr 07 '17 at 03:29

0 Answers0