Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What are the rules regarding chaining of "==" and "!=" in Python

Tags:

python

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.

like image 324
ereOn Avatar asked Jun 22 '12 09:06

ereOn


People also ask

Can you chain == in Python?

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 !=

Does Python allow chained comparison?

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.

What is the use of != operator in Python?

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.

Is == A comparison operator in Python?

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 ( != ).


3 Answers

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

like image 40
Loïc Faure-Lacroix Avatar answered Oct 08 '22 11:10

Loïc Faure-Lacroix


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).

like image 117
lvc Avatar answered Oct 08 '22 11:10

lvc


Check here: http://docs.python.org/reference/expressions.html#not-in

like image 33
Daren Thomas Avatar answered Oct 08 '22 10:10

Daren Thomas