Using any() and all()
Concepts covered: Boolean Operators
One question about a whole sequence
any(iterable) returns True if at least 1 item is truthy, and all(iterable) returns True if every item is. Pass either one a generator expression, the parenthesised form of a generator. A loop with a flag then becomes 1 line that reads like the question: is any latency over 100 ms, is every count present? When the generator expression is the only argument, its own parentheses can go.
latencies = [40, 250, 90, 300]
for ms in latencies:
if ms > 100:
slow_found = True
break
else:
slow_found = False
slow_found = any(ms > 100 for ms in latencies)They stop at the first deciding item
any() stops at the first truthy item, since 1 is enough, and all() stops at the first falsy item. The generator below prints each value as it is checked, so the output shows where each call stopped.
def checked(values):
for value in values:
print("checking", value)
yield value > 100
latencies = [40, 250, 90, 300]
print(any(checked(latencies)))
print(all(checked(latencies)))Output:
checking 40 checking 250 True checking 40 False
Out of 4 values, any() needed 2 checks and all() needed 1. Stopping early pays off when each check is slow, such as opening a file or calling a service. It also pays off when the iterable is a generator over millions of rows, because the rows after the deciding one are never produced.
Empty input and other traps
any([]) is False, since no item is truthy, and all([]) is True, since no item fails. That second rule is sound logic and a real hazard. A quality gate written as all(row > 0 for row in batch) passes an empty batch, so an upstream outage that delivers 0 rows looks clean. Test for emptiness first with short-circuit and: if batch and all(row > 0 for row in batch):.
row_counts = [120, 0, 45]
print(all(row_counts))
print(all(count is not None for count in row_counts))
empty_batch = []
print(all(row > 0 for row in empty_batch))
print(bool(empty_batch and all(row > 0 for row in empty_batch)))Output:
False True True False
Passing raw values tests their truthiness, and 0 is falsy. all(row_counts) is False because 1 table loaded 0 rows, even when the question was whether every count arrived. Write the condition you mean inside the generator expression, here count is not None. Pass raw values only when truthiness is the test.
Both calls share 1 generator. What does this print?
changes = [-2, 4, 6]
positive = (c > 0 for c in changes)
print(any(positive))
print(all(positive))- True, then False: all() reaches -2 and finds it is not positive
- True, then an error: a generator cannot be passed to a second call
- False, then False: both calls read -2 first and stop there
- True, then True: any() used up -2 and 4, so all() sees only 6
Capstone: a batch quality gate
The last example combines a batch generator with both checks. Order totals arrive in batches of 3. A batch with any negative total is rejected, and a clean batch that contains a 0 is loaded with a warning. The short final batch goes through the same gate.
def batches(items, size):
batch = []
for item in items:
batch.append(item)
if len(batch) == size:
yield batch
batch = []
if batch:
yield batch
order_totals = [25, 40, 0, 12, -5, 30, 18]
for number, batch in enumerate(batches(order_totals, 3), start=1):
if not all(total >= 0 for total in batch):
print("batch", number, "rejected:", batch)
elif any(total == 0 for total in batch):
print("batch", number, "loaded with a zero:", batch)
else:
print("batch", number, "loaded:", batch)Output:
batch 1 loaded with a zero: [25, 40, 0] batch 2 rejected: [12, -5, 30] batch 3 loaded: [18]
not all(total >= 0 for total in batch) and any(total < 0 for total in batch) mean the same thing, by De Morgan's laws from the control flow track. Choose the one that matches how the rule is written down.
About this lesson
This section is part of the Loops: Advanced lesson on DataDriven, the home of data engineering. Lessons cover SQL, Python, Spark, data modeling and pipeline architecture, and each section pairs its explanation with worked examples and practice you run as you go.