What are the rules regarding chaining of "==" and "!=" in Python
python
Solution
This works with all comparison operators - eg, you can also do:
>>> 4 < 5 < 6
True
>>> 4 < 5 !=2
True
In general, according to the documentation, `a op1 b op2 c` where `op1` and `op2` are any of: `<`, `>`, `!=`, `==`, `<=`, `>=`, `is` , `is not`, `in` or `not in` will give the same result as:
a op1 b and b op2 c
The docs also say that this can work with arbitrarily many comparisons, so:
>>> 5 != '5' != 'five' != (3+2)
True
Which can be a slightly confusing result sometimes since it seems to say `5 != (3+2)` - each operand is only compared with the ones immediately adjacent to it, rather than doing all possible combinations (which mightn't be clear from examples using only `==`, since it won't affect the answer if everything defines `__eq__` sanely).
Problem
This morning, I find myself writing something like: ``` if (a == b == c): # do something ``` And was surprised that it gave me the expected result. I thought it would behave as: ``` if ((a == b) == c): # do something ``` But it obviously didn't. It seems Python is treating the first statement differently from the second, which is nice but I couldn't find any documentation or explanation regarding this. I tested and got this: ``` In [1]: 2 == 2 == 2 Out[1]: True In [2]: (2 == 2) == 2 Out[2]: False ``` Would someone care to explain me what are the rules regarding such "chaining" of `==` (or `!=`) ? Thank you very much.