8

I've recently stumbled over this expression:

True == False in (False,)

It evaluates to False, but I don't understand why. True == False is False and False in (False,) is True, so both (to me) plausible possibilities

True == (False in (False,))

and

(True == False) in (False,)

evaluate to True, as I would have expected. What is going wrong here?

Turion
  • 5,684
  • 4
  • 26
  • 42
  • 7
    possible duplicate of [Why does (1 in \[1,0\] == True) evaluate to False?](http://stackoverflow.com/questions/9284350/why-does-1-in-1-0-true-evaluate-to-false) – agf Mar 27 '12 at 12:15

1 Answers1

10

I believe this is a corner case of Python's comparison-operator chaining. It gets expanded to

 (True == False) and (False in (False,))

which evaluates to False.

This behavior was intended to match conventional math notation (e.g. x == y == z meaning that all three are equal, or 0 <= x < 10 meaning x is in the range [0, 10)). But in is also a comparison operator, giving the unexpected behavior.

Mechanical snail
  • 29,755
  • 14
  • 88
  • 113
  • Does this make sense in Python, because I can see what is happening but the in operator has a completely different function to == so why does it undergo this comparison operator chaining? – jamylak Mar 27 '12 at 12:26
  • `in` is like the others in that it looks at two values and returns a bool, according to the relation between the two values. – Mechanical snail Mar 27 '12 at 12:28
  • 1
    In addition, it is useful to note that this expression is quivalent to `False and True` which will evaluate to `False`, due to [short circuit evaluation](http://en.wikipedia.org/wiki/Short-circuit_evaluation). – Burhan Khalid Mar 27 '12 at 12:32
  • 1
    @burhan `False and True` evaluates to `False` no matter what -- short circuiting behavior has nothing to do with it. – agf Mar 27 '12 at 12:42
  • Well how about `True and True and False and True`? The last value is never evaluated, which is what I think was @burhan's point. – yurisich Mar 27 '12 at 15:10