Meaning
Checks that every element in an iterable satisfies a condition, raising AssertionError if any element fails. Use for quick sanity‑checks that a collection meets a required property.
Primary Function
Validation
Communicative Purpose
Expresses that all items must satisfy a given predicate before proceeding
Pattern
assert all(condition for item in iterable)
Core Structure
assert all(... for ... in ...)
Função primária
Validation
Propósito comunicativo
Expresses that all items must satisfy a given predicate before proceeding
Situações de gatilho
Data validation: ensure all numbers in a list are positive before processing; Unit testing: assert that a collection satisfies a predicate across test cases; Data pipeline: guard against invalid records during batch transformation
Contextos
General Python scripts, data‑processing pipelines, scientific computing code, unit‑test suites, educational examples
Padrão
assert all(condition for item in iterable)
Estrutura central
assert all(... for ... in ...)
Slots de substituição
condition: expression involving the loop variable; iterable: expression yielding an iterable collection
Colocados típicos
- assert
- all
- generator expression
- for
Substituições comuns
- Using an explicit loop with if not condition: raise AssertionError
- using any(... ) for opposite checks
- employing list comprehensions with assert len([...]) == len(iterable)
Erros comuns
Writing list comprehensions inside assert (creates an unnecessary list); forgetting the parentheses around the generator expression; relying on assert for runtime validation in production where the -O flag disables it
Similar / contraste
any(... for ...) – checks that at least one element satisfies the predicate; plain assert condition – validates a single boolean, not a collection; explicit loops with raise – more verbose but works even when asserts are stripped
Interferências
Coming from languages without a built‑in all: developers may write a manual loop expecting the same brevity; from C/C++ where assert is a macro that cannot contain generator expressions
Família do chunk
- assertion
- validation
- guard_clause
- generator_expression
Nuance
Do not use for side‑effect checks; remember assert statements can be removed with the -O optimization flag, so they are unsuitable for mandatory validation in production code; generator expression evaluates lazily, which is efficient for large iterables
Efeito pragmático
Catches invalid data early, making failures easier to locate and preventing downstream errors
Dica de memória
All positive? Assert all
Nota
Assert statements are removed when Python is run with the -O optimization flag, so they should not be used for mandatory validation in production code.
Upgrade path
def validate_positive(iterable): for i, x in enumerate(iterable): if x <= 0: raise ValueError(f"Element {i} is not positive: {x}") return iterable
Log in to save chunks.