3
In[19]: x = None
In[20]: y = "Something"
In[21]: x is None == y is None
Out[21]: False
In[22]: x is None != y is None ## What's going on here?
Out[22]: False
In[23]: id(x is None)
Out[23]: 505509720
In[24]: id(y is None)
Out[24]: 505509708

Why is Out[22] false? They have different ids, so it's not an identity problem....

NewToPis
  • 33
  • 2

2 Answers2

6

Chained expressions are evaluated from left to right, besides, comparisons is and != have the same precedence, so that your expression is evaluated as:

(x is None) and (None!= y) and (y is None)
#---True----|------True-----|--- False---|
#-----------True------------|
#------------------False-----------------|

To change the order of evaluation, you should put some parens:

>>> (x is None) != (y is None)
True

Also note that the first expression x is None == y is None was a fluke, or rather the red herring, as you'll get the same results if you place some parens in the required positions. It's probably why you assumed the order should start with the is first, then the != in the second case.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
1

Your x is None != y is None is "chained comparisons". A more typical example is 3 < x < 9. Which means the same as (3 < x) and (x < 9). So in your case, with operators is and !=, that's this:

(x is None) and (None != y) and (y is None)

Which is false because y is None is false.

Stefan Pochmann
  • 27,593
  • 8
  • 44
  • 107