Search code examples
pythonconditional-operator

Using ternary if-else in python expect with and-or keywords


I've recently seen on this website that you can use the syntax

var = cond and value1 or value2

Instead of the conventional ternary syntax

var = value1 if cond else value2

I've since failed to find the user that said it or any articles online related to this topic, but after trying it in my code it seems to work as expected. Can someone please clarify if this syntax is actually valid or if this is just a fluke?


Solution

  • It doesn't always work. For example,

    True and False or None
    

    returns None, while

    False if True else None
    

    returns False.

    I recommend reading the language spec, on boolean operators, which says:

    The expression x and y first evaluates x; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

    The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

    Note that neither and nor or restrict the value and type they return to False and True, but rather return the last evaluated argument. This is sometimes useful, e.g., if s is a string that should be replaced by a default value if it is empty, the expression s or 'foo' yields the desired value.