Python’s all(): Check Your Iterables for Truthiness

Python

When programming, you’ll often need to check if all the items in an iterable are truthy. Coding this functionality repeatedly can be annoying and inefficient. Luckily, Python provides the built-in all() function to solve this problem. This function takes an iterable and checks all its items for truth value, which is handy for finding out if those items have a given property or meet a particular condition.

Python’s all() is a powerful tool that can help you write clean, readable, and efficient code in Python.

In this tutorial, you’ll learn how to:

Check if all the items in an iterable are truthy by using all()
Use all() with different iterable types
Combine all() with comprehensions and generator expressions
Distinguish between all() and the Boolean and operator

To complement this knowledge, you’ll code several examples that showcase exciting use cases of all() and highlight the many ways to use this function in Python programming.

To understand the topics in this tutorial, you should have basic knowledge of several Python concepts, such as iterable data structures, Boolean types, expressions, operators, list comprehensions, and generator expressions.

Free PDF Download: Python 3 Cheat Sheet

Evaluating the Truth Value of Items in Iterables

A pretty common problem in programming is determining if all the items in a list or array are truthy or not. For example, you may have the following list of conditions:

5 > 2
1 == 1
42 < 50

To figure out if these conditions are true, you need to iterate over them and test every condition for truthiness. In this example, you have that 5 > 2 is true, 1 == 1 is true, and 42 < 50 is also true. As a result, you can say that all these conditions are true. If at least one of the conditions were false, then you would say that not all the conditions are true.

Note that as soon as you find a falsy condition, you can stop evaluating conditions because, in that case, you already know the final result: not all are true.

To solve this problem by writing custom Python code, you can use a for loop to iterate over each condition and evaluate it for truthiness. Your loop will iterate until it finds a falsy item, at which point it’ll stop because you already have a result:

>>>>>> def all_true(iterable):
for item in iterable:
if not item:
return False
return True

This function takes an iterable as an argument. The loop iterates over the input argument while the conditional if statement checks if any item is falsy using the not operator. If an item is falsy, then the function immediately returns False, signaling that not all the items are true. Otherwise, it returns True.

This function is quite generic. It takes an iterable, which means you can pass in a list, tuple, string, dictionary, or any other iterable data structure. To check if the current item is true or false, all_true() uses the not operator to invert the truth value of its operand. In other words, it returns True if its operand evaluates to false and vice versa.

Python’s Boolean operators can evaluate the truth value of expressions and objects, which guarantees that your function can take iterables containing objects, expressions, or both. For example, if you pass in an iterable of Boolean expressions, then not just evaluates the expression and negates the result.

Here’s all_true() in action:

>>>>>> bool_exps = [
5 > 2,
1 == 1,
42 < 50,
]
>>> all_true(bool_exps)
True

Because all the expressions in the input iterable are true, not negates the result, and the if code block never runs. In that case, all_true() returns True.

Something similar happens when the input iterable holds Python objects and non-Boolean expressions:

>>>>>> objects = [“Hello!”, 42, {}]
>>> all_true(objects)
False

>>> general_expressions = [
5 ** 2,
42 3,
int(“42”)
]
>>> all_true(general_expressions)
True

>>> empty = []
>>> all_true(empty)
True

In the first example, the input list contains regular Python objects, including a string, a number, and a dictionary. In this case, all_true() returns False because the dictionary is empty and evaluates to false in Python.

To perform truth value testing on objects, Python has an internal set of rules for objects that evaluate as false:

Inherently negative constants, like None and False
Numeric types with a zero value, like 0, 0.0, 0j, Decimal(“0”), and Fraction(0, 1)
Empty sequences and collections, like “”, (), [], {}, set(), and range(0)
Objects that implement .__bool__() with a return value of False or .__len__() with a return value of 0

Read the full article at https://realpython.com/python-all/ »

[ Improve Your Python With 🐍 Python Tricks 💌 – Get a short & sweet Python Trick delivered to your inbox every couple of days. >> Click here to learn more and see examples ]