The Built-In any() Function

by Christoph Schiessl on Python

Some time ago, I published an article presenting the built-in all(iterable) function. The idea behind this function was that it returns True, if all elements of the iterable convert to True (according to the Standard Truth Testing Procedure). The opposite of all(), is the built-in function any(iterable), which the offical documentation explains as follows:

Return True if any element of the iterable is true. If the iterable is empty, return False.

Furthermore, the docs also point out that any() is equivalent to the following function (this is not the actual implementation, but it's equivalent to it):

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

Here is a quick demonstration:

Python 3.12.1 (main, Jan 26 2024, 21:58:30) [GCC 13.2.1 20230801] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> any([])                          # empty iterable
>>> any([False, False, False])       # all elements are False
>>> any([False, False, True, False]) # one element is True
>>> any([True, False, True, False])  # multiple elements are True
>>> any([0, 1, 0])                   # one element converts to True
>>> any([0, 1, 0, 2])                # multiple elements convert to True

Similar to all(iterable), we can also rewrite any(iterable) in terms of functools.reduce():

import functools

def any(iterable) -> bool:
    return bool(functools.reduce(lambda x, y: x or y, iterable, False))

Nothing unexpected here.

By the way, this last implementation is almost equivalent to the implementation given by the docs. The difference is that reduce() iterates over the whole iterable, but the implementation from the docs early exits when it encounters the first element that converts to True. This can make a real difference in performance if you imagine a very long iterable with a truthy element in the beginning. Due to the early exit, it only needs to evaluate the first element of the iterable, but the reduce() version has to look at all elements no matter what.

If you are pedantic, you could even argue that the version based on reduce() has a bug: The Standard Truth Testing Procedure calls __bool__() (or __len__()) on all elements of the iterable and in theory these calls could have side-effects, even though they are not supposed to have any. As I said, this argument is quite pedantic and probably irrelevant in practice.

Anyway, that's everything for today. Thank you for reading, and see you next time!

Ready to Learn More Web Development?

Join my Mailing List to receive one article per week.

I send one email per week on building performant and resilient Web Applications with Python, JavaScript and PostgreSQL. No spam. Unscubscribe at any time.

Continue Reading?

Here are a few more Articles for you ...

The Built-In callable() Function

Learn about the callable() function in Python. This article explains how everything in Python is potentially callable, including classes and instances.

By Christoph Schiessl on Python

The Built-In min() and max() Functions

Python's min() and max() functions can take an iterable or multiple positional parameters, and support a key parameter for custom comparisons.

By Christoph Schiessl on Python

Boolean Operators and Short-Circuiting

Fully understand Python's boolean operators for negation, conjunction, and disjunction. Master operator precedence and short-circuiting.

By Christoph Schiessl on Python

Christoph Schiessl

Hi, I'm Christoph Schiessl.

I help you build robust and fast web applications.

I'm available for hire as a freelance web developer, so you can take advantage of the more than a decade of experience I have collected working on many projects across several industries. Most of my clients are building web-based SaaS applications in a B2B context and depend on my expertise in various capacities.

More often than not, my involvement includes hands-on development work using technologies like Python, JavaScript, and PostgreSQL. Furthermore, if you already have an established team, I can support you as a technical product manager with a passion for simplifying complex processes. Lastly, I'm also an avid writer and educator who takes pride in breaking down technical concepts into the simplest possible terms.