Search code examples
pythonconditional-statementsexpressionshortcut

Python: shortcut conditional expression


the shortcut conditional expression :
expression1 if condition else expression2
x=1 if a>3 else 2
But: can I have 2 expressions at the start ?
x=1,b=3 if a>3 else 2

Thanks to > idontknow, solution is >

    previousTime,BS_Count=(db_row_to_list[0][14],BS_Count+1) if db_row_to_list[0][14] is not None else (db_row_to_list[0][3],BS_Count)

Solution

  • Not quite. For something this, it would be possible to use an if statement.

    if a > 3:
        x = 1
        b = 3
    else:
        x = 2
        b = None
    

    If you want everything to become a oneliner, you can use tuple unpacking in Python. What tuple unpacking does is basically take the elements from a tuple and store them as variables, instead of elements of a tuple.

    An application of this concept would be something like this:

    x, b = (1, 3) if a > 3 else (2, None)
    

    Note that it is a oneliner! 🤗

    EDIT: To answer your question in the updated context:

    You can use the following, shorter code. I think the effect will be the same.

    a = 3
    b = 7
    c = 6
    a, b = (8, b+1) if c > 3 else (5, b)
    print(a, b)