Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Usage of the "==" operator for three objects

Is there any computational difference between these two methods of checking equality between three objects?

I have two variables: x and y. Say I do this:

>>> x = 5
>>> y = 5
>>> x == y == 5
True

Is that different from:

>>> x = 5
>>> y = 5
>>> x == y and x == 5
True

What about if they are False?

>>> x = 5
>>> y = 5
>>> x == y == 4
False

And:

>>> x = 5
>>> y = 5
>>> x == y and x == 4
False

Is there any difference in how they are calculated?

In addition, how does x == y == z work?

Thanks in advance!

like image 957
Rushy Panchal Avatar asked Dec 09 '12 22:12

Rushy Panchal


1 Answers

Python has chained comparisons, so these two forms are equivalent:

x == y == z
x == y and y == z

except that in the first, y is only evaluated once.

This means you can also write:

0 < x < 10
10 >= z >= 2

etc. You can also write confusing things like:

a < b == c is d   # Don't  do this

Beginners sometimes get tripped up on this:

a < 100 is True   # Definitely don't do this!

which will always be false since it is the same as:

a < 100 and 100 is True   # Now we see the violence inherent in the system!
like image 78
Ned Batchelder Avatar answered Sep 22 '22 00:09

Ned Batchelder