all() is the logical counterpart to any(): it short-circuits and returns False the instant it finds a falsy element, without checking the rest. On an empty iterable it returns True, vacuously, since there are no elements that could violate the 'all are true' condition — the standard mathematical convention that an empty conjunction is true.
1Understanding all()
all() is the logical counterpart to any(): it short-circuits and returns False the instant it finds a falsy element, without checking the rest. On an empty iterable it returns True, vacuously, since there are no elements that could violate the 'all are true' condition — the standard mathematical convention that an empty conjunction is true.
An empty iterable being considered 'all true' trips people up — double check whether an empty input should really count as every condition being satisfied in your specific logic.
ages = [22, 25, 19, 30]
all_adults = all(age >= 18 for age in ages)
print(all_adults)2Practical Example
Here is a real-world application of all() showing how it is used in production Python code.
form_fields = {"name": "Alice", "email": "a@x.com", "phone": ""}
is_complete = all(form_fields.values())
print(is_complete)3Best Practices
Follow these guidelines when working with all():
1. Use all() with a generator expression instead of a manual loop with a flag variable to check that every item passes a check
2. Combine all() with a generator expression, not a list comprehension, so it can short-circuit on the first failure
3. Explicitly handle the empty-iterable case if the default vacuous-true behavior isn't what you want
Tip: An empty iterable being considered 'all true' trips people up — double check whether an empty input should really count as every condition being satisfied in your specific logic.
ages = [22, 25, 19, 30]
all_adults = all(age >= 18 for age in ages)
print(all_adults)