pythonif-statementmultiple-return-values

How to check the value of one of the variable from multiple returned values in an IF statement in Python


Does anybody have an idea, how to check the value of a variable a == 0 from an multiple return value function in a single IF statement like below,

if (a, b, c = some_function()) == 0: #currently it is wrong
    ...
    ...
else:
    ...
    ...

def some_function():
    return 0, 123, "hello"

Solution

  • First unpack the return values to variables, then check the value of the variable.

    You can use _ as variable name to indicate that the value is not used.

    a, _, _ = some_function()
    if a == 0:
        # ...
    

    Or if you don't need to access any of the return values later at all, you can use indexing:

    if some_function()[0] == 0:
        # ...
    

    But that is less readable, because you don't get to give a name to the return values to document their meaning.

    It would be tempting to use the "walrus operator" :=, but it does not support iterable unpacking (which is used in the first example).