0

Suppose I have the following line of code:

print("valley" in "hillside" == False)

Since the precedence of in and == is equivalent in Python, I expected the operations to be performed from left to right, producing True as the output.

However, in actuality, when I run this line of code, I get False.

I have noticed that adding brackets around "valley" in "hillside" results in True as the output but I don't seem to understand why it's necessary in the first place...

nugget_boi
  • 107
  • 1
  • 10

1 Answers1

3

Both in and == are comparison operators, so the parser treats

print("valley" in "hillside" == False)

the same as

print("valley" in "hillside" and "hillside" == False)

See the section on Comparisons in the Python language reference for more details, in particular this note:

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

chepner
  • 497,756
  • 71
  • 530
  • 681