all()

The built-in all() function evaluates whether all elements in an iterable are truthy, returning True if they’re and False otherwise:

Python
>>> all([True, True, True])
True

>>> all([True, True, False])
False

>>> all([False, False, False])
False

all() Signature

Python Syntax
all(iterable)

Arguments

Argument Description
iterable An iterable object, like a list, tuple, or string

Return Value

  • If all elements in the iterable are truthy, all() returns True.
  • If any element is falsy, all() returns False.
  • If the iterable is empty, all() returns True.

all() Examples

With a list of truthy values:

Python
>>> all(["Hello!", 42, (1, 2, 3)])
True

With a list containing some falsy elements:

Python
>>> all(["", 42, {}, 0])
False

With a list of Boolean expressions as an argument:

Python
>>> all([5 > 2, 1 == 1, 42 < 50])
True

With an empty list:

Python
>>> all([])
True

all() Common Use Cases

The most common use cases for the all() function include:

  • Checking if all elements in an iterable evaluate to true
  • Verifying if all items in an iterable satisfy a certain condition
  • Cleaning data by filtering out elements with falsy values

all() Real-World Example

Imagine you have a CSV file with employee data:

CSV employees.csv
name,job,email
"Linda","Technical Lead",""
"Joe","Senior Web Developer","joe@example.com"
"Lara","Project Manager","lara@example.com"
"David","","david@example.com"
"Jane","Senior Python Developer","jane@example.com"

You want to filter out rows with empty fields. To achieve this, you can use all() as follows:

Python
>>> import csv
>>> with open("employees.csv", "r") as csv_file:
...     raw_data = csv.reader(csv_file)
...     _ = next(raw_data)  # Skip the headings
...     clean_data = [row for row in raw_data if all(row)]
...

>>> print(*clean_data, sep="\n")
['Joe', 'Senior Web Developer', 'joe@example.com']
['Lara', 'Project Manager', 'lara@example.com']
['Jane', 'Senior Python Developer', 'jane@example.com']

This code reads the CSV file and uses a list comprehension to filter out rows containing any empty fields. The all() function helps streamline the data-cleaning process by efficiently identifying rows with complete data.

Tutorial

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

In this step-by-step tutorial, you'll learn how to use Python's all() function to check if all the items in an iterable are truthy. You'll also code various examples that showcase a few interesting use cases of all() and highlight how you can use this function in Python.

basics best-practices python

For additional information on related topics, take a look at the following resources:


By Leodanis Pozo Ramos • Updated Nov. 22, 2024 • Reviewed by Dan Bader