static_rtti
static_rtti

Reputation: 56282

Implementing .all() for a list of booleans?

Numpy has a great method .all() for arrays of booleans, that tests if all the values are true. I'd like to do the same without adding numpy to my project. Is there something similar in the standard libary? Otherwise, how would you implement it?

I can of course think of the obvious way to do it:

def all_true(list_of_booleans):
    for v in list_of_booleans:
        if not v:
            return False
    return True

Is there a more elegant way, perhaps a one-liner?

Upvotes: 0

Views: 94

Answers (2)

mdml
mdml

Reputation: 22882

There is a similar function, called all().

Upvotes: 2

Martijn Pieters
Martijn Pieters

Reputation: 1122342

There is; it is called all(), surprisingly. It is implemented exactly as you describe, albeit in C. Quoting the docs:

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

def all(iterable):
    for element in iterable:
        if not element:
            return False
    return True

New in version 2.5.

This is not limited to just booleans. Note that this takes an iterable; passing in a generator expression means only enough of the generator expression is going to be evaluated to test the hypothesis:

>>> from itertools import count
>>> c = count()
>>> all(i < 10 for i in c)
False
>>> next(c)
11

There is an equivalent any() function as well.

Upvotes: 5

Related Questions