any() and all(): Quick Logical Checks
Checking multiple conditions is a very common task in Python.
Whether you’re validating data, enforcing rules, or filtering values, you often need to answer simple questions:
- Does any item satisfy this condition?
- Do all items satisfy this condition?
That’s exactly what any() and all() are designed for.
Understanding any()
any() returns True if at least one element in the iterable is truthy.
values = [0, "", None, 5]
any(values)
# True
As soon as a truthy value is found, evaluation stops.
Understanding all()
all() returns True only if every element in the iterable is truthy.
values = [1, 2, 3]
all(values)
# True
If even one falsy value is found, the result is False.
A common pattern without any() / all()
numbers = [2, 4, 6, 8]
is_valid = True
for n in numbers:
if n % 2 != 0:
is_valid = False
break
This works, but it’s verbose and easy to clutter with extra logic.
The same logic with all()
numbers = [2, 4, 6, 8]
is_valid = all(n % 2 == 0 for n in numbers)
The intent becomes immediately clear: all numbers must be even.
Combining with conditions
names = ["Alice", "Bob", ""]
has_empty_name = any(name == "" for name in names)
This reads almost like plain English.
A common mistake to avoid
Be careful when mixing any() or all() with complex expressions:
# Hard to read — avoid this
is_valid = all(
(x := compute(x)) > 0 and x < 10
for x in values
)
If the logic becomes dense, split it into steps. Readability always comes first.
Conclusion
In practice, any() and all() help you write code that focuses on intent, not mechanics.
Whenever you find yourself writing loops just to check conditions, these two functions are often the cleaner solution.