Python Language Chain Comparisons


Example

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

The general form is

a OP b OP c OP d ...

Where OP represents one of the multiple comparison operations you can use, and the letters represent arbitrary valid expressions.

Note that 0 != 1 != 0 evaluates to True, even though 0 != 0 is False. Unlike the common mathematical notation in which x != y != z means that x, y and z have different values. Chaining == operations has the natural meaning in most cases, since equality is generally transitive.

Style

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

Side effects

As soon as one comparison returns False, the expression evaluates immediately to False, skipping all remaining comparisons.

Note that the expression exp in 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.