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

229 views Asked by At

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"
2

There are 2 answers

1
mkrieger1 On BEST ANSWER

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).

1
Prune On

This is the closest I was able to get with the walrus operator. My apologies for closing the ticket without checking completely enough.

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

if (my_tuple := some_function() )[0] == 0:
    print ("Check worked")
else:
    print ("Check failed")

a, b, c = my_tuple

This is very close to mkrieger1's answer (upvoted), adding only a demonstration of receiving a single return value in the "walrus" assignment.