Pages

Topics

Tools

↑↓navigate↵openescclose
All guides

Python any and all: How to Use Them Effectively

Learn how Python's any() and all() work, including short-circuiting behavior, practical examples, and when to choose each for cleaner condition checks.

~5 min readPython
#Python built-ins#any() function#all() function#short-circuiting
A visual representation of Python's any() and all() functions showing short-circuit evaluation with boolean logic gates.

Python's any() and all() are built-in functions that evaluate an iterable of values and return a single boolean. They are commonly used to replace explicit loops that check conditions across a collection. any() returns True if at least one element in the iterable is truthy, while all() returns True only if every element is truthy. Both stop evaluating as soon as the result is determined, which is known as short-circuiting.

What any() and all() Do

The syntax is straightforward: any(iterable) and all(iterable). Each function takes a single iterable and returns a boolean. The functions rely on Python's truthiness rules, so values like 0, None, empty containers, and False are considered falsy; everything else is truthy.

python
numbers = [1, 2, 3] print(any(numbers)) # True, because at least one is truthy print(all(numbers)) # True, because all are truthy mixed = [0, 1, 2] print(any(mixed)) # True, because 1 is truthy print(all(mixed)) # False, because 0 is falsy

These functions are equivalent to a manual loop, but they are more concise and less error-prone. For example, any(iterable) is equivalent to:

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

Similarly, all(iterable) is equivalent to:

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

Understanding this equivalence clarifies the short-circuiting behavior: both functions stop iterating as soon as the final result is known.

How Short-Circuiting Affects Runtime

Short-circuiting means any() stops at the first truthy value, and all() stops at the first falsy value. This can significantly reduce work when the iterable is a generator or a lazy sequence, because you avoid evaluating elements that don't affect the result.

Consider a generator that yields values with side effects, such as logging or database queries:

python
def generate_values(): for i in range(10): print(f"Yielding {i}") yield i print(any(generate_values())) # Output: # Yielding 0 # Yielding 1 # True

Here, any() stops after the second value because 1 is truthy. If you had converted the generator to a list first, all ten values would have been produced unnecessarily. This behavior is especially important when dealing with expensive computations or I/O.

For all(), the same principle applies: it stops at the first falsy element. For example:

python
def is_even(x): print(f"Checking {x}") return x % 2 == 0 print(all(is_even(x) for x in [2, 4, 5, 6])) # Output: # Checking 2 # Checking 4 # Checking 5 # False

The function never checks 6 because 5 is not even, so the result is already False.

Practical Use Cases for any()

A common use case is checking whether at least one element in a collection satisfies a condition. For example, validating that a user has at least one admin role:

python
user_roles = ["editor", "viewer"] has_admin = any(role == "admin" for role in user_roles)

Another scenario is checking if any file in a directory has a certain extension:

python
import os files = os.listdir(".") has_python_file = any(f.endswith(".py") for f in files)

You can also use any() to combine conditions that are already stored in a collection. For example, if any([a, b, c]): is equivalent to if a or b or c: when a, b, and c are already computed. This is clearer when the number of conditions is dynamic or large.

Practical Use Cases for all()

all() is useful for validating that every element meets a requirement. For instance, checking that all required fields are present in a form:

python
required_fields = ["name", "email", "password"] form_data = {"name": "Alice", "email": "alice@example.com", "password": ""} all_present = all(form_data.get(field) for field in required_fields)

Another example is verifying that all numbers in a list are positive:

python
numbers = [1, 2, 3] all_positive = all(n > 0 for n in numbers)

all() is also handy for checking that every element in a nested structure is not empty, or that all values in a dictionary meet a condition.

Edge Cases: Empty Iterables and Generators

A critical edge case is the behavior of any() and all() on empty iterables. any([]) returns False because there is no truthy element. all([]) returns True because there is no falsy element. This is consistent with mathematical logic: the universal quantifier over an empty set is true, and the existential quantifier is false.

This behavior can be surprising in code that expects at least one element. For example:

python
items = [] if all(item.is_valid() for item in items): # This block executes, which may be unintended.

If you need to ensure the iterable is non-empty, check len() or use a separate condition.

When using generators, remember that they are consumed as they are iterated. If you call any() on a generator and then call all() on the same generator, the second call works on the values that remain or on an exhausted generator if the first call consumed it completely. This can lead to subtle bugs:

python
values = (0 for _ in range(3)) print(any(values)) # False, consumes all values print(all(values)) # True, because the generator is now empty

To avoid this, convert the generator to a list if you need to evaluate it multiple times, or restructure your logic.

Choosing Between any() and all()

The decision between any() and all() depends on the logical condition you need to express. Use any() when you want to know if at least one element satisfies a predicate. Use all() when every element must satisfy the predicate. There is no performance difference between the two; both short-circuit and have the same time complexity in the worst case.

However, the choice affects readability. For example, all(not condition for item in items) has the same final truth value as not any(condition for item in items) due to De Morgan's laws, but the former is often clearer if the intent is "no item violates the rule." Conversely, any(condition) is more direct than not all(not condition).

Consider the following two expressions that check whether a list contains no negative numbers:

python
numbers = [1, 2, 3] # Using all() all_positive = all(n > 0 for n in numbers) # Using any() no_negatives = not any(n < 0 for n in numbers)

Both are correct, but all() reads more naturally for this validation.

Performance and Memory Considerations

When using any() or all(), the iterable you pass matters. If you pass a list comprehension, Python creates the entire list in memory before evaluating the function. For large datasets, this can be wasteful. Instead, use a generator expression, which evaluates lazily and avoids building an intermediate list.

python
# Inefficient: creates a list of booleans result = any([x > 10 for x in range(1000000)]) # Efficient: generator expression result = any(x > 10 for x in range(1000000))

The generator version still short-circuits, so it may not even iterate through the entire range. The list version always iterates all elements to build the list, which is slower and uses more memory.

This distinction is critical in performance-sensitive code, especially when dealing with large collections or infinite generators. For example, you can safely use any() with an infinite generator as long as a truthy value appears early:

python
from itertools import count # Terminates because 3 is found before the generator can run forever print(any(x == 3 for x in count()))

If you used a list comprehension with an infinite generator, it would never terminate. Therefore, prefer generator expressions when the iterable is large or potentially unbounded.

Another operational consideration is that, in CPython, any() and all() are implemented in C, so the iteration overhead is typically lower than an equivalent pure-Python loop. However, the predicate you pass inside a generator expression still runs in Python, so the overhead of the predicate dominates for complex conditions. In such cases, the readability gain from using these functions often outweighs micro-optimizations.

Try matching browser tools

All tools

Small utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.

All Python guides

More in Python

All Python guides

The guides filed next to this one in Python, in library order.