>>> "f" in "foo"
True
>>> "f" in "foo" == True
False
I'm confused why the second expression is False. I see ==
has higher precedence than in
. But then I would expect to get an exception, which is what happens when I add parentheses:
>>> "f" in ("foo" == True)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument of type 'bool' is not iterable
It seems the expression is only True when foo
is on both sides of ==
, like so:
>>> "f" in "foo" == "foo"
True
>>> "f" in "foo" == "bar"
False
What am I missing? What is Python actually calculating here?
In Python, comparison operators chain.
That is why 1 < 2 < 3 < 4
works and evaluates to True.
See https://docs.python.org/3/reference/expressions.html#comparisons
in
and ==
are such operators, so by this mechanism
"f" in "foo" == True
means
("f" in "foo") and ("foo" == True)