Search code examples
pythonsyntaxcomparison

How does interval comparison work?


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?


Solution

  • 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