Test if all elements of a python list are False

Posted on

Question :

Test if all elements of a python list are False

How to return ‘false’ because all elements are ‘false’?

The given list is:

data = [False, False, False]
Asked By: thunder

||

Answer #1:

Using any:

>>> data = [False, False, False]
>>> not any(data)
True

any will return True if there’s any truth value in the iterable.

Answered By: falsetru

Answer #2:

Basically there are two functions that deal with an iterable and return True or False depending on which boolean values elements of the sequence evaluate to.

  1. all(iterable) returns True if all elements of the iterable are considered as true values (like reduce(operator.and_, iterable)).

  2. any(iterable) returns True if at least one element of the iterable is a true value (again, using functional stuff, reduce(operator.or_, iterable)).

Using the all function, you can map operator.not_ over your list or just build a new sequence with negated values and check that all the elements of the new sequence are true:

>>> all(not element for element in data)

With the any function, you can check that at least one element is true and then negate the result since you need to return False if there’s a true element:

>>> not any(data)

According to De Morgan’s law, these two variants will return the same result, but I would prefer the last one (which uses any) because it is shorter, more readable (and can be intuitively understood as “there isn’t a true value in data”) and more efficient (since you don’t build any extra sequences).

Answered By: Alexey Orlenko

Answer #3:

Come on, guys, he asked for returning True whether there was any True.
Saying the same, False when all are False.

any(data)
Answered By: Oscar Developper

Leave a Reply

Your email address will not be published.