ZetCode

Python any & all builtins

last modified October 30, 2026 Python 3.15

In this article we show how to work with the any and all builtins in Python.

Both functions take an iterable and return a boolean value. They test the truthiness of the elements: False, None, zero, and empty strings and containers are falsy; all other values are truthy.

Python any

The any builtin function returns True if any element of the iterable is truthy. If the iterable is empty, it returns False.

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

The any function is equivalent to the above code. It stops at the first truthy element.

any_simple.py
vals = [False, False, True, False, False]

if any(vals):
    print('There is a truthy value in the list')
else:
    print('There is no truthy value in the list')

print(any([0, '', None]))
print(any([0, '', 'falcon']))
print(any([]))

With the any function, we check if there is a truthy value in the list.

print(any([0, '', None]))
print(any([0, '', 'falcon']))
print(any([]))

Zero, an empty string, and None are all falsy. The non-empty string 'falcon' is truthy. An empty list contains no truthy value.

$ python any_simple.py
There is a truthy value in the list
False
True
False

Short-circuit evaluation

The any and all functions are usually called with a generator expression. The generator produces values lazily, so the functions can stop as soon as the result is known.

any_generator.py
nums = [3, 7, 12, 5, 21, 8]


def is_big(n):
    print(f'checking {n}')
    return n > 10


print(any(is_big(n) for n in nums))
print('---')
print(any([is_big(n) for n in nums]))

The is_big function prints each number it checks.

print(any(is_big(n) for n in nums))

With a generator expression, the checking stops at 12, the first number greater than ten. The extra parentheses of the generator can be omitted when it is the only argument.

print(any([is_big(n) for n in nums]))

The list comprehension evaluates all numbers before any even starts. The result is the same, but the work is wasted.

$ python any_generator.py
checking 3
checking 7
checking 12
True
---
checking 3
checking 7
checking 12
checking 5
checking 21
checking 8
True

Python any practical example

Our next goal is to find out if there are some users older than the specified age.

users_age.py
from datetime import date

users = [
    {'name': 'John Doe', 'date_of_birth': '1987-11-08', 'active': True},
    {'name': 'Jane Doe', 'date_of_birth': '1996-02-03', 'active': True},
    {'name': 'Robert Brown', 'date_of_birth': '1977-12-12', 'active': True},
    {'name': 'Lucia Smith', 'date_of_birth': '2002-11-17', 'active': False},
    {'name': 'Patrick Dempsey', 'date_of_birth': '1994-01-04', 'active': True}
]


def age(born, today):
    had_birthday = (today.month, today.day) >= (born.month, born.day)
    return today.year - born.year - (not had_birthday)


today = date.today()
limit = 40

births = [date.fromisoformat(user['date_of_birth']) for user in users]

if any(age(born, today) > limit for born in births):
    print(f'There are users older than {limit}')
else:
    print(f'There are no users older than {limit}')

We have a list of users. Each user is represented as a dictionary. One of the keys of the dictionary is the date of birth.

def age(born, today):
    had_birthday = (today.month, today.day) >= (born.month, born.day)
    return today.year - born.year - (not had_birthday)

The age function computes the age in whole years. The tuples are compared element by element; if the person has not had a birthday yet this year, we subtract one. The boolean not had_birthday counts as 0 or 1.

births = [date.fromisoformat(user['date_of_birth']) for user in users]

With a list comprehension, we transform the date_of_birth strings into date objects. The fromisoformat method parses dates in the YYYY-MM-DD format.

if any(age(born, today) > limit for born in births):

We pass a generator of boolean values to the any function. It returns True as soon as it finds a user older than forty.

$ python users_age.py
There are users older than 40

Python all

The all builtin function returns True if all elements of the iterable are truthy, or if the iterable is empty.

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

The all function is equivalent to the above code. It stops at the first falsy element.

all_simple.py
vals = [True, False, True, True, True]

if all(vals):
    print('All values are truthy')
else:
    print('Not all values are truthy')

print(all([1, 'a', [0]]))
print(all([1, 'a', []]))
print(all([]))

With the all function, we check if all values are truthy.

print(all([1, 'a', [0]]))
print(all([1, 'a', []]))

The list [0] is truthy, because it is not empty; its content does not matter. The empty list makes the second call return False.

$ python all_simple.py
Not all values are truthy
True
False
True

Python all practical example

We want to find out if all users are active.

users_active.py
users = [
    {'name': 'John Doe', 'occupation': 'gardener', 'active': True},
    {'name': 'Jane Doe', 'occupation': 'teacher', 'active': True},
    {'name': 'Robert Brown', 'occupation': 'driver', 'active': True},
    {'name': 'Lucia Smith', 'occupation': 'hair dresser', 'active': False},
    {'name': 'Patrick Dempsey', 'occupation': 'programmer', 'active': True}
]

if all(user['active'] for user in users):
    print('All users are active')
else:
    print('There are inactive users')

inactive = next(user['name'] for user in users if not user['active'])
print(f'First inactive user: {inactive}')

We have a list of users. The users have the active property.

if all(user['active'] for user in users):

With the all function we check if all users are active.

inactive = next(user['name'] for user in users if not user['active'])

The all function only tells us that some user is inactive. To find out which one, we use the next function with a generator expression; it returns the first matching element.

$ python users_active.py
There are inactive users
First inactive user: Lucia Smith

The all function and empty iterables

The all function returns True for an empty iterable. This is called vacuous truth: there is no element that fails the test. Sometimes this is not what we want.

empty_iterable.py
def all_passed(scores, limit=50):
    return all(score >= limit for score in scores)


print(all_passed([70, 85, 52]))
print(all_passed([70, 45, 52]))
print(all_passed([]))


def all_passed_strict(scores, limit=50):
    return bool(scores) and all(score >= limit for score in scores)


print(all_passed_strict([]))

The all_passed function reports that all students passed even when there are no scores at all.

return bool(scores) and all(score >= limit for score in scores)

The strict version also requires the list to be non-empty.

$ python empty_iterable.py
True
False
True
False

Combining any and all

The functions are often combined to express a set of rules. In the next example, we validate passwords.

password_rules.py
def check_password(pwd):
    rules = {
        'at least 8 characters': len(pwd) >= 8,
        'an uppercase letter': any(c.isupper() for c in pwd),
        'a lowercase letter': any(c.islower() for c in pwd),
        'a digit': any(c.isdigit() for c in pwd),
        'no spaces': not any(c.isspace() for c in pwd),
    }

    if all(rules.values()):
        return 'ok'

    missing = [rule for rule, passed in rules.items() if not passed]
    return 'missing: ' + ', '.join(missing)


for pwd in ['falcon', 'Falcon2026', 'falcon 2026', 'FALCON']:
    print(f'{pwd!r:14} {check_password(pwd)}')

Each rule is a boolean value stored in a dictionary.

'an uppercase letter': any(c.isupper() for c in pwd),

A string is an iterable of characters. The rule is met if any character is an uppercase letter.

'no spaces': not any(c.isspace() for c in pwd),

The expression not any(...) means that no element meets the condition. It is equivalent to all(not c.isspace() for c in pwd).

if all(rules.values()):
    return 'ok'

The password is valid if all rules are met. Otherwise, we list the failed rules.

$ python password_rules.py
'falcon'       missing: at least 8 characters, an uppercase letter, a digit
'Falcon2026'   ok
'falcon 2026'  missing: an uppercase letter, no spaces
'FALCON'       missing: at least 8 characters, a lowercase letter, a digit

Checking nested data

Generator expressions with several for clauses and nested calls let us check nested data structures.

nested_data.py
matrix = [
    [1, 2, 3],
    [4, -5, 6],
    [7, 8, 9],
]

print(all(len(row) == len(matrix[0]) for row in matrix))
print(any(x < 0 for row in matrix for x in row))
print(all(any(x % 2 == 0 for x in row) for row in matrix))

We check a matrix stored as a list of rows.

print(all(len(row) == len(matrix[0]) for row in matrix))

All rows have the same length as the first one.

print(any(x < 0 for row in matrix for x in row))

The two for clauses go through all elements. There is a negative value in the matrix.

print(all(any(x % 2 == 0 for x in row) for row in matrix))

Each row contains at least one even number.

$ python nested_data.py
True
True
True

The any function vs the in operator

To test if a specific value is in a sequence, we use the in operator. The any function is for conditions that cannot be expressed as a simple equality.

any_vs_in.py
words = ['sky', 'forest', 'Cloud', 'rock']

print('rock' in words)
print('cloud' in words)
print(any(word.lower() == 'cloud' for word in words))

found = next((word for word in words if len(word) > 4), None)
print(found)

found = next((word for word in words if len(word) > 10), None)
print(found)

The in operator compares values exactly, so 'cloud' does not match 'Cloud'.

print(any(word.lower() == 'cloud' for word in words))

With any, we can do a case-insensitive comparison.

found = next((word for word in words if len(word) > 4), None)

When we need the matching element itself, we use next. The second argument is the default value returned when no element matches.

$ python any_vs_in.py
True
False
True
forest
None

Source

Python built-in functions

In this article we have worked with the any and all builtin functions. See also Python any builtin and Python all builtin.

Author

My name is Jan Bodnar, and I am a passionate programmer with extensive programming experience. I have been writing programming articles since 2007. To date, I have authored over 1,400 articles and 8 e-books. I possess more than ten years of experience in teaching programming.

List all Python tutorials.