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.
Chaining with the comparison operator == returns True only if all values are equal. If there is even one different value, False is returned. Be careful when using the comparison operator !=
Python supports chaining of comparison operators, which means if we wanted to find out if b lies between a and c we can do a < b < c , making code super-intuitive. Python evaluates such expressions like how we do in mathematics.
In Python != is defined as not equal to operator. It returns True if operands on either side are not equal to each other, and returns False if they are equal.
Python has six comparison operators: less than ( < ), less than or equal to ( <= ), greater than ( > ), greater than or equal to ( >= ), equal to ( == ), and not equal to ( != ).
As far as I know the example you point out isn't chaining.
2 == 2 == 2
is like (2 == 2) and ( 2 == 2)
which turns out to be True and True
while
(2 == 2) == 2
is like (True) == 2
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).
Check here: http://docs.python.org/reference/expressions.html#not-in
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With