Search code examples
pythonif-statementreturn-value

and/or instead of if/else


After working through some toy examples, I could see that it's possible to emulate the ternary operator of "c" condition?value_if_true:value_if_false in Python using condition and value_if_true or value_if_false. I would like to know if it works in all cases and if it is better or worse than using value_if_true if condition else value_if_false.


Solution

  • It's strictly worse: the conditional expression was added to the language specifically to avoid the problem with using ... and ... or ... incorrectly.

    # 0 is falsy
    >>> True and 0 or 5
    5
    >>> 0 if True else 5
    0
    

    PEP-308 references "FAQ 4.16" for other workarounds to the problems with and/or, though I can no longer track down what FAQ is being referred to, but it was eventually decided that a dedicated conditional expression was preferable.

    For example, one could write

    (True and [0] or [3])[0]
    

    to ensure that the true-result is truthy, so that the false-result isn't returned. The false-result has to be adjusted as well so that regardless of what result is produced, it can be indexed to finally provide the intended result.