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 theiterable
is true. If theiterable
is empty, returnFalse
.
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
False
>>> any([False, False, False]) # all elements are False
False
>>> any([False, False, True, False]) # one element is True
True
>>> any([True, False, True, False]) # multiple elements are True
True
>>> any([0, 1, 0]) # one element converts to True
True
>>> any([0, 1, 0, 2]) # multiple elements convert to True
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!