Why does (1 in [1,0] == True) evaluate to False?

Question:

When I was looking at answers to this question, I found I didn’t understand my own answer.

I don’t really understand how this is being parsed. Why does the second example return False?

>>> 1 in [1,0]             # This is expected
True
>>> 1 in [1,0] == True     # This is strange
False
>>> (1 in [1,0]) == True   # This is what I wanted it to be
True
>>> 1 in ([1,0] == True)   # But it's not just a precedence issue!
                           # It did not raise an exception on the second example.

Traceback (most recent call last):
  File "<pyshell#4>", line 1, in <module>
    1 in ([1,0] == True)
TypeError: argument of type 'bool' is not iterable

Thanks for any help. I think I must be missing something really obvious.


I think this is subtly different to the linked duplicate:

Why does the expression 0 < 0 == 0 return False in Python?.

Both questions are to do with human comprehension of the expression. There seemed to be two ways (to my mind) of evaluating the expression. Of course neither were correct, but in my example, the last interpretation is impossible.

Looking at 0 < 0 == 0 you could imagine each half being evaluated and making sense as an expression:

>>> (0 < 0) == 0
True
>>> 0 < (0 == 0)
True

So the link answers why this evaluates False:

>>> 0 < 0 == 0
False

But with my example 1 in ([1,0] == True) doesn’t make sense as an expression, so instead of there being two (admittedly wrong) possible interpretations, only one seems possible:

>>> (1 in [1,0]) == True
Asked By: Peter Wood

||

Answers:

Python actually applies comparison operator chaining here. The expression is translated to

(1 in [1, 0]) and ([1, 0] == True)

which is obviously False.

This also happens for expressions like

a < b < c

which translate to

(a < b) and (b < c)

(without evaluating b twice).

See the Python language documentation for further details.

Answered By: Sven Marnach