Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplify Chained Comparison

Tags:

python

pycharm

People also ask

What chained comparison operators?

These comparison operators are <, <=, >, >=, ==, != , is, is not, in, not in. The precedence of these operators are same, and the precedence is lesser than arithmetic, bitwise and shifting operators. These operators can be arranged arbitrarily. They will be used as a chain.

What is a chained comparison Python?

Chain of multiple comparisonsComparisons 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).


In Python you can "chain" comparison operations which just means they are "and"ed together. In your case, it'd be like this:

if start <= x <= end:

Reference: https://docs.python.org/3/reference/expressions.html#comparisons


It can be rewritten as:

start <= x <= end:

Or:

r = range(start, end + 1) # (!) if integers
if x in r:
    ....