Search code examples
pythonbooleancomparisonoperatorscomparison-operators

In python, what is the meaning of a<b<c?


Is if a[start] <= target < a[mid] the same as a[start] <= target and target<a[mid] and a[start] < a[mid]? (I think its not, but visually it looks like both are the same) How does this work under the hood? Searched on SO, but couldn't find an answer.


Solution

  • The

    if a[start] <= target < a[mid]:
    

    is essentially[*] the same as

    if a[start] <= target and target < a[mid]:
    

    (If true, it follows that a[start] < a[mid], since <= should be transitive.)

    [*] There is one subtlety that doesn't apply to your case but is worth knowing about. The chained form evaluates the middle expression just once, whereas the expanded form evaluates it twice. This could matter if the middle expression is costly to compute or has some side effects (such as printing something to the screen).

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