Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Testing equality of three values

Tags:

python

Does this do what I think it does? It seems to me that yes. I am asking to be sure.

if n[i] == n[i+1] == n[i+2]:     return True 

Are these equal?

if n[i] == n[i+1] and n[i+1] == n[i+2]:     return True 
like image 390
graywolf Avatar asked Dec 10 '12 17:12

graywolf


People also ask

How can we check if three variables are equal?

Use the equality operator to check if multiple variables are equal, e.g. if a == b == c: . The expression will compare the variables on the left-hand and right-hand sides of the equal signs and will return True if they are equal. Copied!

How do you test multiple variables against a single value?

Use the or operator to test multiple variables against a single value, e.g. if a == 'a' or b == 'a' or c == 'a': . The or operator will return True if the value is stored in at least one of the variables.

How do you test a variable against multiple values in Python?

To test multiple variables x , y , z against a value in Python, use the expression value in {x, y, z} . Checking membership in a set has constant runtime complexity. Thus, this is the most efficient way to test multiple variables against a value.


1 Answers

It is equivalent to but not equal to, since accesses are only performed once. Python chains relational operators naturally (including in and is).

The easiest way to show the slight difference:

>>> print(1) == print(2) == print(3) 1 2 3 True >>> print(1) == print(2) and print(2) == print(3) 1 2 2 3 True 

print() always returns None, so all we are doing is comparing Nones here, so the result is always True, but note that in the second case, print(2) is called twice, so we get two 2s in the output, while in the first case, the result is used for both comparisons, so it is only executed once.

If you use pure functions with no side-effects, the two operations end up exactly the same, but otherwise they are a little different.

like image 50
Ignacio Vazquez-Abrams Avatar answered Oct 08 '22 22:10

Ignacio Vazquez-Abrams