0

I noticed strange behaviour with python operator in and == precedence and associativity.

Here is a snippet example:

b = {}
b['foo'] = 'coo'
print('foo' in b)               # prints True, expected True
print(('foo' in b) == True)     # prints True, expected True
print('foo' in b == True)       # prints False, expected True due to operator precedence
print('foo' in (b == True))     # exception: bool type is not iterable

In the above, we have 'foo' in b == True being evaluated to False. However the precedence of in and == are the same but based on the operator associativity in should be evaluated first before ==.

Are there any explanations for how python interprets this expression to better understand what is happening here or have I encountered something strange?

  • 1
    `in`, for some reason, is lumped in with the other comparison operators. Yes, `x in y` has to compare `x` to *elements* of `y`, but I'm not sure any code becomes easier to read by having it subject to comparison chaining. – chepner Mar 29 '23 at 12:51

0 Answers0