I’m using python 2.7.2 with built-in IDLE on windows 7 x64, and found a very strange thing:
>>> a = "aaa"
>>> b = "aaa"
>>> print a is b
True
>>> print a == b
True
>>> print "%s , %s" % (id(a), id(b))
43872224 , 43872224
>>>
This is normal, but, if the string contains a space:
>>> x = "x x"
>>> y = "x x"
>>> print x is y
False
>>> print x == y
True
>>> print "%s , %s" % (id(x), id(y))
43872008 , 43872128
>>>
Notice x is y is False! And they have different ids!
I tried these code in PyCharm, everything returns True, so I think this is may be a bug of IDLE.
Isn’t it? Or do I miss something?
Python’s is operator actually checks to see if the parameters it’s passed are the same object, so in this case whilst they are the same value they’re not the same object.
This has actually been discussed here before: with a lot more detail as well, worth checking out.