How it works
any returns True when it finds a truthy item; all returns False when it finds a falsy item. They return Boolean values, unlike and and or, which can return operands.
Both stop as soon as the result is known. A generator expression allows conditions to be calculated on demand. A list comprehension calculates every condition before the function begins.
Choices and common mistakes
any on an empty input is False; all on an empty input is True. Add a separate nonempty requirement when no records should be rejected.
Do not depend on every predicate running for its side effects. Short-circuiting deliberately skips unnecessary calls.
Try it yourself
Check that a list of order quantities is nonempty and every quantity is positive. Try [], [2, 3] and [2, 0], and explain both checks.
Syntax
any(condition(item) for item in items)
all(condition(item) for item in items)Examples
Find an overdue task
Decide whether any task requires attention.
days_late = [0, 3, 0]
print(any(days > 0 for days in days_late))- The generator turns each number into a comparison result. Zero is not overdue, but three is.
- any stops after the true comparison for three. It does not need to evaluate the last entry.
- Use this when a dashboard needs one warning indicator rather than a complete list of overdue tasks.
- Expected output: True
Require at least one valid quantity
Handle the empty-input rule explicitly.
for quantities in [[], [2, 3], [2, 0]]:
valid = bool(quantities) and all(q > 0 for q in quantities)
print(valid)- bool(quantities) distinguishes an empty list from a populated one. and avoids the second check when the list is empty.
- all then checks positivity. The zero in the final list makes that result false.
- An order-validation rule often requires both an item and a valid quantity; all alone does not express both requirements.
- Expected output: False True False
See short-circuiting
Make the order of predicate evaluation visible.
def acceptable(value):
print("checked", value)
return value > 0
print(all(acceptable(value) for value in [2, 0, 5]))- acceptable prints before returning its comparison. all requests values until the zero produces False.
- There is no checked 5 line because the final predicate is never called. The last line is the aggregate result.
- Keep validation predicates free of required side effects; use a full loop when every item needs a diagnostic.
- Expected output: checked 2 checked 0 False
Best practices
- any on an empty input is False; all on an empty input is True. Add a separate nonempty requirement when no records should be rejected.
- Do not depend on every predicate running for its side effects. Short-circuiting deliberately skips unnecessary calls.
Runtime & versions
Python interpreter. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
Python language reference