Does Python’s `all` function use short circuit evaluation?

Yes, it short-circuits:

>>> def test():
...     yield True
...     print('one')
...     yield False
...     print('two')
...     yield True
...     print('three')
...
>>> all(test())
one
False

From 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

So when it returns False, then the function immediately breaks.

Leave a Comment