How to check if all elements of a list match a condition?
Master System Design with Codemia
Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.
Introduction
In Python, the standard way to check whether every element in a list satisfies a condition is all(...). The main design question is not the syntax, but how to handle empty input, mixed types, and callers that need more than a simple True or False.
Use all With a Generator Expression
The most direct pattern is a generator expression passed to all.
This is efficient because all short-circuits. It stops at the first failure, so expensive predicates are not evaluated unnecessarily.
Wrap Reusable Checks in a Helper
If the same style of validation appears in multiple places, wrap it in a helper so the call site reads like intent instead of plumbing.
This pattern keeps domain logic readable and makes unit testing easier.
Decide What Empty Input Means
Python defines all([]) as True. That is mathematically sensible, but it is not always what an application wants.
If a list must contain at least one element, say so directly instead of relying on readers to remember how all behaves on empty iterables.
Handle Mixed Types Deliberately
If the predicate assumes numbers, then None or a string may raise an exception. In that case, a loop can be clearer than one dense generator expression.
This style is often easier to maintain when validation has multiple steps.
Return Failure Details When Needed
A bare boolean is sometimes too weak. If the caller needs to know why validation failed, return the first bad index and value.
That extra detail is valuable in validation libraries, ETL jobs, and tests.
Apply the Same Pattern to Structured Data
The predicate does not have to be a tiny numeric test. It can validate dictionaries, records, or model objects.
The same all(...) pattern still works, but the predicate is now meaningful at the business level.
Common Pitfalls
The most common mistake is forgetting that all([]) returns True and accidentally accepting empty input that should fail.
Another common issue is writing predicates that raise exceptions on mixed-type data instead of returning False cleanly. Developers also sometimes compress too much logic into one generator expression when a small helper or loop would be easier to read.
Summary
- Use
all(predicate(x) for x in items)as the normal Python pattern. - Remember that
all([])isTrue, and override that if the domain requires non-empty input. - Prefer a loop when validation has multiple steps or type checks.
- Return failure details when the caller needs more than a boolean.
- Keep predicates readable, especially for structured data.

