Why do I get differing results with these two examples of the is operator?
>>> a = "1234"
>>> b = "1234"
>>> a is b
True
>>> a = "12 34"
>>> b = "12 34"
>>> a is b
False
What exactly does is do here? I understand that it is supposed to compare memory addresses, but I don’t see how that causes these results.
isis not an equality operator. It checks to see if two variables refer to the same object. If you were to do this:then
a is bwould beTrue, since they refer to the same object.The cases you present are due to implementation details of the Python interpreter. Since strings are immutable, in some cases, creating two of the same string will yield references to the same object — i.e., in your first case, the Python interpreter only creates a single copy of
"1234", andaandbboth refer to that object. In the second case, the interpreter creates two copies. This is due to the way the interpreter creates and handles strings, and, as an implementation detail, should not be relied upon.