Compare two boolean expressions in python

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 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 this is not an identity issue ....

+3


source to share


2 answers


You x is None != y is None

have chained comparisons in yours . "A more typical example is 3 < x < 9

. This means that (3 < x) and (x < 9)

. So, in your case, with operators is

and !=

, that is:

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

      



It is false because it y is None

is false.

+1


source


Related expressions are evaluated from left to right, in addition, comparisons is

and !=

have the same precedence, so your expression evaluates as:

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

      

To change the order of evaluation, you have to put some symbols:



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

      


Also note that the first expression x is None == y is None

was a fluke, or rather a red herring, as you'll get the same results if you put some of the parsers in the right positions. This is probably why you assumed that the order should start at is

first and then !=

in the second case.

+6


source







All Articles