You can compare multiple items with multiple comparison operators with chain comparison. For example
x > y > z
is just a short form of:
x > y and y > z
This will evaluate to
True only if both comparisons are
The general form is
a OP b OP c OP d ...
OP represents one of the multiple comparison operations you can use, and the letters represent arbitrary valid expressions.
0 != 1 != 0evaluates to
True, even though
0 != 0is
False. Unlike the common mathematical notation in which
x != y != zmeans that
zhave different values. Chaining
==operations has the natural meaning in most cases, since equality is generally transitive.
There is no theoretical limit on how many items and comparison operations you use as long you have proper syntax:
1 > -1 < 2 > 0.5 < 100 != 24
The above returns
True if each comparison returns
True. However, using convoluted chaining is not a good style. A good chaining will be "directional", not more complicated than
1 > x > -4 > y != 8
As soon as one comparison returns
False, the expression evaluates immediately to
False, skipping all remaining comparisons.
Note that the expression
a > exp > b will be evaluated only once, whereas in the case of
a > exp and exp > b
exp will be computed twice if
a > exp is true.