Testing equality of three values

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

Solution 1:

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.

Solution 2:

Yes, however, when the comparisons are chained the common expression is evaluated once, when using and it's evaluated twice. In both cases the second comparison is not evaluated if the first one is false, example from the docs:

Comparisons can be chained arbitrarily, e.g., x < y <= z is equivalent to x < y and y <= z, except that y is evaluated only once (but in both cases z is not evaluated at all when x < y is found to be false).