Why does (1 == 2 != 3) evaluate to False in Python?

Question:

Why does (1 == 2 != 3) evaluate to False in Python, while both ((1 == 2) != 3) and (1 == (2 != 3)) evaluate to True?

What operator precedence is used here?

Asked By: Mo Xu

||

Answers:

This is due to the operators’ chaining phenomenon. The Python documentation explains it as:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent
to x < y and y <= z, except that y is evaluated only once (but in both
cases z is not evaluated at all when x < y is found to be false).

And if you look at the precedence of the == and != operators, you will notice that they have the same precedence and hence applicable to the chaining phenomenon.

So basically what happens:

>>>  1==2
=> False
>>> 2!=3
=> True

>>> (1==2) and (2!=3)
  # False and True
=> False
Answered By: Kaushik NP

A chained expression, like A op B op C where op are comparison operators, is in contrast to C evaluated as (Comparisons in the Python Reference Manual):

A op B and B op C

Thus, your example is evaluated as

1 == 2 and 2 != 3

which results to False.

Answered By: clemens
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.