star4z
star4z

Reputation: 389

Use boolean array as condition

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?

Upvotes: 0

Views: 139

Answers (4)

Mark Beilfuss
Mark Beilfuss

Reputation: 602

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

Upvotes: 2

A.J. Uppal
A.J. Uppal

Reputation: 19264

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

Upvotes: 0

chepner
chepner

Reputation: 531165

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>

Upvotes: 4

grundic
grundic

Reputation: 4921

Use all:

if all(conditions):
  ...

Upvotes: 0

Related Questions