15

Say I have a bunch of variables that are either True or False. I want to evaluate a set of these variables in one if statement to see if they are all False like so:

if var1, var2, var3, var4 == False:
    # do stuff

Except that doesn't work. I know I can do this:

if var1 == False and var2 == False and var3 == False and var4 == False:
    # do stuff

But that's fairly ugly - especially if these if statements are going to occur a lot in my code. Is there any sort of way I can do this evaluation with a cleaner syntax (like the first example)?

Rauffle
  • 767
  • 2
  • 7
  • 14

8 Answers8

34

You should never test a boolean variable with == True (or == False). Instead, either write:

if not (var1 or var2 or var3 or var4):

or use any (and in related problems its cousin all):

if not any((var1, var2, var3, var4)):

or use Python's transitive comparisons:

if var1 == var2 == var3 == var4 == False:
Community
  • 1
  • 1
phihag
  • 245,801
  • 63
  • 407
  • 443
  • 7
    `not any(...)` is the Pythonic way to do it for the "all False" case, and `all(...)` is for the "all True" case. – Steven T. Snyder Feb 29 '12 at 18:39
  • `any((var1, var2, var3, var4))` means all will be evaluated regardless which if you were using expensive functions would be pretty inefficient and rather defeats the purpose of any and short circuiting – Padraic Cunningham Dec 06 '15 at 20:06
  • @PadraicCunningham `var1`, `var2` etc. are all variables, hence the `var`. If they are function calls, you would of cause use something else. – phihag Dec 06 '15 at 20:25
7

How about this:

# if all are False
if not any([var1, var2, var3, var4]):
    # do stuff

or:

# if all are True
if all([var1, var2, var3, var4]):
    # do stuff

These are easy to read, since they are in plain English.

Steven T. Snyder
  • 5,139
  • 2
  • 23
  • 55
3

if all(not v for v in (var1, var2, var3, var4)):

That's for the "all false" branch. For "all true", just do if all((var2, var2, var3, var4)):.

ben w
  • 2,392
  • 10
  • 17
3

You can do:

if var1 and var2 and var3 and var4:
     do stuff
soulcheck
  • 34,060
  • 6
  • 82
  • 89
1

What about a custom function?

function ListObjectsEqualTo(myList, toValue):
    for i in myList:
        if i != toValue:
            return False
    return True

Now you can use it

if ListObjectsEqualTo((var1, var2, var3, var4), False):
    # do stuff
v1Axvw
  • 3,054
  • 3
  • 24
  • 40
1

You could do:

if var1 == var2 == var3 == var4 == False:
  do_stuff()

But, if the variables evaluate to true or false, you could also do this:

if var1 and var2 and var3 and var4:
  do_stuff()

Or

if all([var1, var2, var3, var4]):
  do_stuff()
mipadi
  • 359,228
  • 81
  • 502
  • 469
1
>>> not any([False, False])
True
>>> not any([True, False])
False
>>> 

Use the any() keyword.

hexparrot
  • 3,133
  • 1
  • 21
  • 31
0

You can use if var1 == var2 == var3 == False:

jbowes
  • 3,764
  • 19
  • 37