all()
Functionby 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 theiterable
are true (or if theiterable
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 exits early 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 an easy-to-use built-in function is available.
In practice, I often map an input_iterable
to another iterable
that consists of bool
s, which I then pass into all()
. Here is a quick example for you:
Python 3.12.2 (main, Feb 17 2024, 11:13:07) [GCC 13.2.1 20230801] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> 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.
I send two weekly emails on building performant and resilient Web Applications with Python, JavaScript and PostgreSQL. No spam. Unscubscribe at any time.
any()
Function
Learn how to use the built-in any()
function in Python to determine if any element in an iterable
is True
, with implementation and performance insights.
By Christoph Schiessl on Python
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
Learn about the Levenshtein distance algorithm, a popular and easy-to-implement way to measure the similarity between two strings.
By Christoph Schiessl on Python