0
>>> a = 1
>>> b = 2
>>> c = 3
>>> a+b is not c
False

Close python, start new session to be sure variables aren't being re-used or anything

>>> a = 293
>>> b = 2
>>> c = 296
>>> a+b is not c-1
True

Why are these different?

  • 4 is not 4 - False (correct)
  • 295 is not 295 - True (incorrect)

EDIT: sorry I don't think I was clear in my question. i'm not asking if is not should be used for value comparison, or if it's equivalent to !=, I'm asking why it produces inconsistent results that vary based on the integer values being evaluated.

Mike
  • 555
  • 3
  • 14
  • 1
    `is not` not for value comparison – mtkilic Dec 07 '18 at 20:14
  • See also: [python 'is not' operator](https://stackoverflow.com/q/4485180/1288) – Bill the Lizard Dec 07 '18 at 20:15
  • i'm not asking if is not should be used for value comparison, or if it's equivalent to !=, I'm asking why it produces inconsistent results that vary based on the integer values being evaluated – Mike Dec 07 '18 at 20:19
  • ...and the implementation details relevant to understanding that behavior are given in our existing Q&A entries on the site. **However**, you shouldn't be writing code that relies on undocumented implementation details at all, and it's utterly unsurprising when code that *is* written in that way breaks. Part of the "based on actual problems that you face" criteria for topicality on this site is that if there's an easy "don't do that" answer available, and no compelling reason not to use it, one no longer *faces an actual problem* once that answer is known. – Charles Duffy Dec 07 '18 at 20:24
  • 1
    What you see is a behaviour of the Python 2 and 3 interpreters, which cache all integers between -5 and 256, so they really are the same object (which is what you compare with the is operator). See also: https://stackoverflow.com/questions/306313/is-operator-behaves-unexpectedly-with-integers – ilmarinen Dec 07 '18 at 20:30
  • The "why" is explained in the second answer to the first duplicate question, including an example that includes your 295 case. – 9769953 Dec 07 '18 at 20:31
  • Thank you ilmarinen, that is actually an answer to my question – Mike Dec 07 '18 at 20:31

0 Answers0