Use all and any in Python
Check iterable values or predicates with short-circuit evaluation, account for empty input, and distinguish truthiness from valid data.
all(iterable) returns True if every encountered value is truthy. It returns False at the first false value. An empty iterable returns True, so validate nonempty input separately when your application requires it.
Check values or a condition
print(all([True, True])) # True
print(all([True, False])) # False
print(all([])) # True
numbers = [2, 4, 6, 8]
print(all(value % 2 == 0 for value in numbers)) # True
print(all(value > 0 for value in numbers)) # True
A generator expression computes one predicate at a time and stops when the answer is known. A list comprehension evaluates every predicate before all starts, so it loses that evaluation advantage and allocates a list.
Understand truthiness
False, None, numeric zero, and empty standard containers are false. A nonempty container is normally true even if its contents are false:
print(all([1, "a", [0]])) # True
print(all([1, "a", 0])) # False
Custom objects can define truth testing through __bool__ or __len__. Those methods can also raise exceptions; all does not turn every failure into False.
Compare any
print(any([False, True])) # True
print(any([])) # False
any stops at the first truthy value. all stops at the first false value. Both consume their input as they inspect it; a partially consumed iterator continues from its current position afterward.
Validate the condition you actually need
fields = ["Alex", "alex@example.com", " "]
complete = all(field.strip() for field in fields)
print(complete) # False
This assumes every field is a string and rejects whitespace-only values. Plain all(fields) would accept the spaces. Neither form validates an email address or phone number; use field-specific validation for that.
For a list of test results, all(result.passed for result in results) checks the attributes. If no test results must be treated as failure, use a separate nonempty check such as bool(results) and all(...). A generator's own truth value does not reveal whether it has any elements.
FAQ
Why is all of an empty list true? There is no counterexample to the condition. That logical convention is useful, but may differ from a business rule that requires at least one record.
How is it different from and? and returns an operand, while all returns a Boolean after inspecting an iterable.
Will it finish on an infinite iterator? Only if it encounters a false value. An infinite stream of truthy values never establishes that all values are true.
References
Contact us
Join the community
to join the community
Try Guance
Start online and pay only for what you use.
Get startedChoose a Guance plan