0

Just a bizar thing I just noticed in Python. If I use a string in Python, the "is" comparison shows the same result as the "==" comparison:

>>> a = "bc"
>>> a is "bc"
True
>>> a == "bc"
True

If I add a slash to the string the first comparison comes out as False:

>>> a = "b/c"
>>> a is "b/c"
False
>>> a == "b/c"
True

Why is this?

Alasdair
  • 298,606
  • 55
  • 578
  • 516
  • 2
    And specifically in Daniel Pryden's answer in the dupe: "when you have two string literals (words that are literally typed into your program source code, surrounded by quotation marks) in your program that have the same value, the Python compiler will automatically intern the strings, making them both stored at the same memory location. (Note that this doesn't always happen, and the rules for when this happens are quite convoluted, so please don't rely on this behavior in production code!)". You've found a case where it happens and another where it doesn't. – Steve Jessop Oct 30 '13 at 11:36
  • Ok, wierd that it works in some cases tho: a=1 gives a True, a=200 gives a True, but a=6000 gives a False. I will stick to ==. And sorry I couldn't find the other question, searching for "is" is never an easy task. – Michael Nieuwenhuizen Oct 30 '13 at 12:31
  • Integers are "interned" up to some fixed limit: `i = 0; while (i + 1 - 1) is i: print i; i += 1`, but that's an implementation detail of CPython. And yes, you should use `==` for equality comparisons, which is any time you don't know for a fact that you want to test identity instead of equality. It's common idiom to use `is` when testing against `None` for example (or Python's other builtin singletons). – Steve Jessop Oct 30 '13 at 12:50

0 Answers0