0

I would like to know if it is a good practice to use tuples instead of separated expressions in a if statement.

is_dog = True
is_brown = False

I would like to do like this:

if (is_dog, is_brown):
    do_something()

Instead of like this:

if is_dog or is_brown:
    do_something()

What is the best practice in this case? Thank you

2
  • 1
    I don't understand, even both is_dog and is_cat is True, if (is_cat, is_dog): will be Trueif (is_cat, is_dog): not equals to if is_dog or is_cat: Commented Apr 7, 2019 at 13:07
  • 1
    You want to take a look at any and all: stackoverflow.com/questions/19389490/… Commented Apr 7, 2019 at 13:07

2 Answers 2

4

There are a few things going on here:

You're using a tuple as the branching value for if. The truthiness of a predicate only indicates if its empty or not, and nothing about its contents:

assert bool(tuple()) is False
assert bool((False, )) is True

Second, if you know in advance the number of items in the tuple, using ors and ands is usually more readable, like you mentioned:

if is_dog or is_cat:
    do_something()

And lastly, you can use any for arbitrary number of values:

values = [is_dog, is_cat, ... more]
if any(values):
    do_something()
Sign up to request clarification or add additional context in comments.

Comments

3

This is not good practice to see if either bool is True:

if (False,False):
    print("it does not do what you think it does")

Output:

it does not do what you think it does

See python truth value testing: any non empty tuple is True-thy

The correct way is:

if a or b:   
    pass

For multiples you can use any():

if any(x for x in (False, True)):
    pass   # will enter here if any part of the tuple is True
else:
    pass   # will enter here if no part of the tuple is True

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.