Why does the statement 1 in (1, 2, 3) == True
return False
in Python?
Is the operator priority in Python ambiguous?
Asked
Active
Viewed 3,025 times
5

IntelliMoonSpirit
- 63
- 1
- 5
1 Answers
10
Because, per the documentation on operator precedence:
Note that comparisons, membership tests, and identity tests, all have the same precedence and have a left-to-right chaining feature as described in the Comparisons section.
The Comparisons section shows an example of the chaining:
Comparisons can be chained arbitrarily, e.g.,
x < y <= z
is equivalent tox < y and y <= z
So:
1 in (1, 2, 3) == True
is interpreted as:
(1 in (1, 2, 3)) and ((1, 2, 3) == True)
If you override this chaining by adding parentheses, you get the expected behaviour:
>>> (1 in (1, 2, 3)) == True
True
Note that, rather than comparing truthiness by equality to True
or False
, you should just use e.g. if thing:
and if not thing:
.

jonrsharpe
- 115,751
- 26
- 228
- 437
-
Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z – 宏杰李 Dec 10 '16 at 13:11
-
@宏杰李 yes that is true - I've literally just added that quote from the docs! – jonrsharpe Dec 10 '16 at 13:11
-
1we got same idea, lol – 宏杰李 Dec 10 '16 at 13:11
-
Also, if you explicitly want to compare to `True` use `stuff is True`, not `stuff == True` – MaxNoe Dec 10 '16 at 14:01