Reputation: 1195
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
Upvotes: 0
Views: 535
Reputation: 51683
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
Upvotes: 3
Reputation: 31349
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 or
s and and
s 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()
Upvotes: 4