10

The following code outputs False, when according to the Python Order of Operations it should output True (the order should be in -> ==, not the other way around). Why is == coming before in?

y = "33"
"3" in y == True

Output

False
Banghua Zhao
  • 1,518
  • 1
  • 14
  • 23
rob
  • 109
  • 3
  • 2
    the `in` and the `==` operator have the same precedence. So they are evaluated from left to right I belive. Why not using `()` so it is clear in the code what do you want? `("3" in "33") == True ` – Netwave Nov 21 '18 at 13:20
  • 13
    Also, this is an instance of *operator chaining*, since `==` and `in` both count as comparison operators. So this is evaluated as `('3' in y) and (y == True)` – juanpa.arrivillaga Nov 21 '18 at 13:24
  • 1
    Also, you never need to compare with True or False. If correctly parenthesized, your statement would mean True == True or False == True – Michal Polovka Nov 21 '18 at 13:26
  • Also, why not simply write `3 in y`? there is no need to check a bool result against bool. You can read about [operator chaining here](https://stackoverflow.com/a/25753528/1918287) – Maor Refaeli Nov 21 '18 at 13:36

2 Answers2

18

The existing answers give helpful advice that you shouldn't compare booleans to True because it's redundant. However, none of the answers actually answer the root question: "why does "3" in y == True evaluate to False?".

That question was answered in a comment by juanpa.arrivillaga:

Also, this is an instance of operator chaining, since == and in both count as comparison operators. So this is evaluated as ('3' in y) and (y == True)

In Python, comparison operators can be chained. For example, if you want to check that a, b, c, and d are increasing, you can write a < b < c < d instead of a < b and b < c and c < d. Similarly, you can check that they are all equal with a == b == c == d.

Chained comparisons are described in the Python documentation here:

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

k_ssb
  • 6,024
  • 23
  • 47
-2

In python, comparisons, memberships tests and identity tests all have the same precedence. The keyword in which checks for membership returns a bool, there is no need for extra compare with a second bool. However, you can group the expressions like so...

y = "33"

("3" in y) == True

Ahmadore
  • 23
  • 1
  • 6
  • 4
    This doesn't answer the question of "why does `"3" in y == True` evaluate to `False`?" – k_ssb Nov 21 '18 at 13:39