The Built-in all() Function

by Christoph Schiessl on [Python]

One of the functions that you are sure to encounter pretty soon when you are working with boolean logic in Python is the built-in all(iterable) function. The official docs describe the function as follows:

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

This is a pretty good explanation, but the suggested implementation is even more revealing:

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

So, the function loops over the elements in the iterable, and as soon as it encounters an element that does not convert to True, it early exits by returning False. There are many other ways to implement this same function. For instance, you could use functools.reduce():

import functools

def all(iterable) -> bool:
    return bool(functools.reduce(lambda x, y: x and y, iterable, True))

Needless to say, these implementations are nothing but tools to explain how all() works. In the real world, you would never implement a function like this by yourself when there is an easy-to-use built-in function available.

In practice, I often map an input_iterable to another iterable that consists of bools, which I then pass into all(). Here is a quick example for you:

def all_double_digit(input_iterable) -> bool:
    return all(map(lambda x: x >= 10 and x <= 99, input_iterable))

assert all_double_digit(range(9,100)) == False # first element is single-digit
assert all_double_digit(range(10,100)) == True
assert all_double_digit(range(10,101)) == False # last element is triple-digit

I hope you get the idea, and please don't hesitate to reach out if you have any questions.