Combining python "in" and "==" operator has confusing behavior

44 Views Asked by At

A buddy of mine is learning python and I saw an odd thing he did with his code:

if ch in input[index] == test[index])

Obviously there's some context missing for that fragment, but interestingly, that if statement gives him his desired behavior. Similarly, the below statement prints True:

print("w" in "w" == "w")

I'm not a python expert, so I don't understand why this happens. I would assume some kind of precedence and/or associativity would bungle things up here and return False or throw an error.

From what I can tell "w" in "w" == "w" is the same as "w" in "w" and "w"== "w", which is rather unintuitive. I'm hoping someone who understands python interpreting can explain why this kind of statement is evaluated in this way.

1

There are 1 best solutions below

0
Andrej Kesely On

This is clearly stated in the documentation (https://docs.python.org/3/reference/expressions.html#comparisons):

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).

In the documentation the operators used are < and <=, but in and == are operators as well, so this applies to case in the question too:

"w" in "w" == "w" is evaluated as "w" in "w" and "w" == "w"