Search code examples
pythonoperator-keywordand-operator

Why 10 and 5 returns 5 and 5 and 10 returns 10 in python? Basically it returns the second int after and operator irrespective of value


I was looking into python "and" operator and found out:

>>> 10 and 5
5
>>> 5 and 10
10

Solution

  • Think of statement logic and which operand determines the value of the entire expression:

    and:

    • the first falsy operand makes the expression False regardless of what comes after
    • if there are only truthy operands, the last one settles it

    Examples:

    >>> 5 and 0
    0
    >>> 0 and 5
    0 
    >>> 5 and 0 and 3
    0 
    >>> 10 and 5
    5
    >>> 5 and 10
    10
    

    or:

    • the first truthy operand makes the expression True regardless of what comes after
    • if there are only falsy operands, the last one settles it

    Examples:

    >>> 5 or 0
    5
    >>> 0 or 5
    5 
    >>> 5 or 0 or 3
    5 
    >>> 10 or 5
    10
    >>> 5 or 10
    5
    

    Shot-Circuit behaviour:

    Note that the rest of the expression is not even evaluated, which is relevant if you chain e.g.function calls or other expressions with side effects:

    >>> 4/0 or 5
    ZeroDivisionError
    >>> 5 or 4/0
    5
    >>> func1() or func2() and func3()
    # func2 and func3 might never be called
    

    Right-Left-Associativity

    This is kind of directly required for the short-circuit behaviour, but not completely intuitive, especially compared to Python's arithmetic operators:

    a or b and c or d == (a or (b and (c or d)))