26

Somehow, this works:

def in_range(min, test, max):
    return min <= test <= max

print in_range(0, 5, 10)  # True
print in_range(0, 15, 10)  # False

However, I can't quite figure out the order of operations here. Let's test the False case:

print 0 <= 15 <= 10  # False
print (0 <= 15) <= 10  # True
print 0 <= (15 <= 10)  # True

Clearly, this isn't resolving to a simple order of operations issue. Is the interval comparison a special operator, or is something else going on?

2
  • related-but-not-quite-duplicate: stackoverflow.com/questions/2452837/python-evaluation-order
    – Wooble
    Jun 26, 2014 at 16:56
  • print (0 <= 15) <= 10 evaluates to True. But It makes no sense to ask True <= 10, even if it is defined by Python. I think in these cases it is best to think "Pythonic"; what is the concept that we are trying to do here? A: We do indeed get the interval comparison as desired. Nov 19, 2019 at 3:20

2 Answers 2

36

Unlike most languages, Python supports chained comparison operators and it evaluates them as they would be evaluated in normal mathematics.

This line:

return min <= test <= max

is evaluated by Python like this:

return (min <= test) and (test <= max)

Most other languages however would evaluate it like this:

return (min <= test) <= max
4
  • 2
    you can even do crazier stuff like a < b <= c < d <= e ... although it starts getting really confusing once you go more than 2 comparisons Jun 26, 2014 at 16:58
  • 2
    So the comparison operations are evalueted left to right, i.e. if min <= test evaluates to False, test <= max is not evaluated? But I guess that in min <= test <= max, test is always evaluated only once, while in the expression (min <= test) and (test <= max), test may be evaluated one or two times (depending on the value of min <= test)? Nov 23, 2017 at 10:46
  • 1
    @HelloGoodbye good question. In min <= test() <= max the test() function will only be evaluated once.
    – Minderov
    Jul 31, 2018 at 18:57
  • @JoranBeasley Or even crazier, a==b==c==0 or a==b==c!=0 (all same non-zero value) or 0<a==b==c (all same positive value) or 0<a<=9>=b>0<c<=9 (a, b, c are 1-9). Any number of any compare operations. Jul 17, 2020 at 17:39
5

As specified in the Python documentation:

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

Formally, if a, b, c, ..., y, z are expressions and op1, op2, ..., opN are comparison operators, then a op1 b op2 c ... y opN z is equivalent to a op1 b and b op2 c and ... y opN z, except that each expression is evaluated at most once.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.