091. Any() And All()
Test whether some or all elements satisfy a condition
091. Any() And All()
Rohan’s RAM manager is collecting snapshots every 5 seconds. Now he needs to answer questions about the whole batch.
He writes three separate for-loops with boolean flags:
# Verbose version
all_safe = True
for snap in snapshots:
if snap['percent'] >= 90:
all_safe = False
break
any_critical = False
for snap in snapshots:
if snap['percent'] >= 95:
any_critical = True
breakA senior dev looks over his shoulder: “That’s 12 lines for two questions Python can answer in two.”
all_safe = all(s['percent'] < 90 for s in snapshots)
any_critical = any(s['percent'] >= 95 for s in snapshots)Why it matters:
all()short-circuits on the firstFalse— it stops scanning the moment one snapshot is critical.any()short-circuits on the firstTrue. On a list of 10,000 snapshots, this can save thousands of iterations.
Rohan adds a third check: are ALL required fields present in every snapshot?
required = {'percent', 'available_mb', 'timestamp'}
complete = all(required.issubset(s.keys()) for s in snapshots)One generator expression. No loops. No flags.
💡 Fun fact: all() and any() both short-circuit — all() stops at the first False, any() stops at the first True. This means all(is_valid(x) for x in huge_list) can return False after checking just the very first element, without scanning millions of items. This is the same optimization as && and || short-circuit evaluation in C/Java.
⚠️ Watch out: all([]) returns True (vacuously true — nothing violated the condition) and any([]) returns False (nothing satisfied the condition). These are mathematically correct but often surprise beginners who expect an empty input to return False for both. Always consider the empty-input case when using all() as a validator.
🤔 Think about it: all(x > 0 for x in numbers) uses a generator expression, so values are checked one at a time. all([x > 0 for x in numbers]) builds the full list first and then checks it. When would the difference matter, and why is the generator version almost always preferable?
Learning objectives
- Use all() to check that every element satisfies a condition
- Use any() to check if at least one element satisfies a condition
- Combine any/all with generator expressions for memory efficiency
- Understand short-circuit evaluation and why it matters for performance
Key concepts
- any
- all
- generator expression
- short-circuit evaluation
Try it
Concept detail
all(iterable) → True if every element is truthy (or iterable is empty). any(iterable) → True if at least one element is truthy.
Use with generator expressions to avoid building intermediate lists: all(x > 0 for x in numbers) — no list created, values checked one at a time any(x > 0 for x in numbers) — stops at first True
Short-circuit behavior: all() stops scanning at the first False element. any() stops scanning at the first True element. On large inputs this saves significant work.
Edge cases: all([]) → True (vacuously true — nothing violated the condition) any([]) → False (nothing satisfied the condition)
Common patterns: all(isinstance(x, int) for x in items) — type-check every element any(x.startswith(“ERROR”) for x in logs) — check if any error lines all(k in d for k in required_keys) — validate dict has all keys
Solution
def all_positive(numbers):
return all(n > 0 for n in numbers)
def has_admin(users):
return any(user["role"] == "admin" for user in users)
def passwords_ok(passwords):
return all(len(pw) >= 8 for pw in passwords)Tests
def test_all_positive_true():
assert all_positive([1, 2, 3]) == True
def test_all_positive_false():
assert all_positive([1, -1, 3]) == False
def test_all_positive_zero():
assert all_positive([1, 0, 3]) == False # zero is NOT positive
def test_all_positive_empty():
assert all_positive([]) == True # vacuously true
def test_has_admin_true():
users = [{"role": "user"}, {"role": "admin"}, {"role": "user"}]
assert has_admin(users) == True
def test_has_admin_false():
users = [{"role": "user"}, {"role": "moderator"}]
assert has_admin(users) == False
def test_passwords_ok_true():
assert passwords_ok(["strongpass", "another1"]) == True
def test_passwords_ok_false():
assert passwords_ok(["strong", "short"]) == False
def test_passwords_ok_exact_8():
assert passwords_ok(["exactly8"]) == True # exactly 8 chars is OK