Python's any() & all()
Master two powerful built-in functions for testing collections, and learn how short-circuit evaluation makes them fast.
What Are any() and all()?
Python provides two built-in functions that answer simple yes/no questions about every item in an iterable (a list, tuple, set, generator, etc.).
A Visual Mental Model
Why Use any() & all()?
You could write a for loop with an if check every time. But any() and all() give you the same result in one readable line.
The Formal Definitions
Short-Circuit Evaluation
Short-circuiting means Python stops scanning the iterable the moment the answer is determined: it doesn't need to look at the rest.
any() vs all(): Key Distinction
| any() | all() | |
|---|---|---|
| Question asked | "Is at least one truthy?" | "Are all truthy?" |
| Returns True when | ≥ 1 truthy element | Every element truthy |
| Returns False when | All elements falsy | ≥ 1 falsy element |
| Short-circuits on | First truthy item | First falsy item |
| Empty iterable | False | True |
| Logic analogy | OR across elements | AND across elements |
The Empty Iterable Edge Case
How to Apply Them
(x > 0 for x in nums) produces True/False per item.if if needed.Example 1: Basic Usage
Example 2: String Validation
Example 3: Proving Short-Circuiting
Generators vs List Comprehensions
Common Patterns in Practice
all(field != "" for field in form_data)any(code >= 400 for code in status_codes)all(os.path.exists(f) for f in file_list)any(keyword in line for line in document)all(test.passed for test in test_results)Common Mistakes
Summary at a Glance
| Scenario | any() | all() |
|---|---|---|
| [True, True, True] | True | True |
| [True, False, True] | True | False |
| [False, False, False] | False | False |
| [] (empty) | False | True |
| Short-circuits on | First True | First False |
| Best used with | Generator expression | Generator expression |
Question 1 of 5
What does any([0, "", None, False]) return?
Question 2 of 5
What does all([]) return, and why?
Question 3 of 5
Given nums = [-3, -1, 0, 2, 5], which elements does Python actually evaluate when running any(n > 0 for n in nums)?
Question 4 of 5
Why is any(x > 10 for x in data) preferred over any([x > 10 for x in data]) when data has millions of items?
Question 5 of 5
Which code correctly checks that every string in a list starts with a capital letter?