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.
This works with all comparison operators – eg, you can also do:
In general, according to the documentation,
a op1 b op2 cwhereop1andop2are any of:<,>,!=,==,<=,>=,is,is not,inornot inwill give the same result as:The docs also say that this can work with arbitrarily many comparisons, so:
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).