0

I was wondering if you can pass an array of conditions as a condition, specifically in Python?

for example:

conditions = [True, False, True, True, False]

if conditions:
    <do stuff>

Python doesn't throw an error when I give it something like this, but I'm not sure if it's doing what I want it to do. Is it actually comparing the whole list? And if so, is it in an and or or fashion? Or is it doing something different, like only comparing the first item?

star4z
  • 377
  • 3
  • 10

4 Answers4

4

Empty lists are "false"; all others are "true". If you want to do stuff if all the conditions are true, use

if all(conditions):
    <do stuff>

If you want to do stuff if any of the conditions are true, use

if any(conditions):
    <do stuff>
chepner
  • 497,756
  • 71
  • 530
  • 681
2

A list will pass an if test if it is non empty. So [] will be false and all other values will be true for the purposes of the test.

If you want to test if any value of a list is True you can use any to do so. If you want to test if all values are true use all in the same way.

Example:

if any(conditions):
     do something
Mark Beilfuss
  • 602
  • 4
  • 12
0

Use all:

if all(conditions):
  ...
grundic
  • 4,641
  • 3
  • 31
  • 47
  • why -1? My answer wasn't useful..? – grundic May 17 '17 at 20:09
  • Different people downvote for different reasons such as: incomplete answers, answers without explanation, or even Python 2 links. You can't know for sure \*shrug\* – vaultah May 17 '17 at 20:15
  • 1
    They should remember though, that they sacrifice (a bit) their rating as well. I can understand when the question was about python and answer was about Peppa Pig, but here... Doh.. – grundic May 17 '17 at 20:18
0

Just use all:

>>> conditions = [True, False, True, True, False]
>>> all(conditions)
False
>>> conditions = [True, True, True, True, True]
>>> all(conditions)
True
>>> 

From the docs:

Return True if all elements of the iterable are true (or if the iterable is empty).

A.J. Uppal
  • 19,117
  • 6
  • 45
  • 76