27

A senior of mine demonstrated it and I want to know if this is a flaw or is there some precedence and operator associativity stuff that justifies it.

>>> False==False in [False]
True
Mathias Müller
  • 22,203
  • 13
  • 58
  • 75
Satwik
  • 1,281
  • 4
  • 18
  • 31
  • 2
    This could be a case of Python's famous comparison operator chaining (so that this would be the same as `False == False and False in [False]`). I'm not sure about that though... – hlt Dec 08 '15 at 18:17
  • Without knowing, but from the answer here: http://stackoverflow.com/questions/34163067/python-why-does-false-false-in-false-returns-true#34163067 - it might be due to the way it is handled. `(False==False) in [False]` – Nicolai Krüger Dec 08 '15 at 18:17
  • substituting `False` with `1` makes it a lot more clearer – letsc Dec 08 '15 at 18:18
  • 3
    @letsc: No it doesn't, because `False` is numerically 0, not 1. – user2357112 Dec 08 '15 at 18:19
  • 6
    @PadraicCunningham no matter what precedence is, `(False == False) in [False]` and `False == (False in [False])` are both `False`. So, it's chaining. – bereal Dec 08 '15 at 18:21

1 Answers1

40

Python's comparison operators chain.

False == False in [False]

is evaluated as

(False == False) and (False in [False])

The middle term participates in both comparisons.

I would prefer that in not chain with the other comparison operators.

Steven Rumbalski
  • 44,786
  • 9
  • 89
  • 119
  • 1
    Is the only reason for chaining operators to make expressions like `x < y < z` legal? Because if that's the case although it's handy, it seems like that's a small benefit in exchange for confusing code like `(False==False in [False])==True` being legal. – Charles Clayton Dec 08 '15 at 18:22
  • 1
    I don't know of a use case for chaining `in` with other comparison operators that produces clear code. – Steven Rumbalski Dec 08 '15 at 18:25
  • 3
    Steven, you can avoid trying to shoot yourself in the foot by simply not doing stupid stuff like this. Nobody is forcing you to write unmaintainable code :-) – Emil Vikström Dec 08 '15 at 18:26