Python any and all: empty iterables and short-circuiting
Understand Python any and all: truth values, empty iterables, nonempty validation and short-circuiting, with an iterator trace and a practice exercise.
You validate a list with all() and get a true result even when the list is empty. Then you replace the list with a generator, and a presence check stops working as expected. There are two separate questions here: does an element exist, and are the elements you visit truthy?
In short
Python's any(iterable) returns True as soon as an element is truthy; all(iterable) returns False as soon as an element is falsy. With no elements, any returns False and all returns True. To require a nonempty list whose elements all satisfy a condition, use bool(values) and all(condition(value) for value in values). An iterator needs a different presence check: bool(iterator) doesn't tell you whether elements remain.
What do any and all test?
They test each element's truth value and return a Boolean. Zero, None, and empty collections are falsy. A nonempty string is truthy, even when its contents spell False.
for values in ([], [0], [0, 2], [2, 3], ["False"], [[]], [[0]]): print(repr(values), any(values), all(values))$ python3 values.py[] False True[0] False False[0, 2] True False[2, 3] True True['False'] True True[[]] False False[[0]] True Trueall([[0]]) is true because its only element is a nonempty list. It doesn't recursively inspect nested collections. Similarly, bool([0]) is true because the list contains an element, while all([0]) is false because that element is zero.
Why does all return True for an empty list?
all looks for a counterexample: one falsy element makes the result false. If iteration finishes without finding one, the result is true. Empty iteration reaches that ending immediately. any looks for a truthy element instead; with no elements, it finds none.
| Input | any | all | Reason |
|---|---|---|---|
[] | False | True | No decisive element |
[0] | False | False | One falsy element |
[0, 2] | True | False | One truthy and one falsy element |
[2, 3] | True | True | All truthy, at least one element |
That rule defines the functions. It doesn't decide whether your program should accept empty input.
How do you reject an empty list during validation?
Add a separate presence check. For a list, bool(values) requires at least one element; all then applies the condition to each element.
def positive_batch(values): return bool(values) and all(value > 0 for value in values)
for values in ([], [2, 3], [2, 0]): print(repr(values), positive_batch(values))print(repr([] and all([])))source = iter([])print(bool(source), all(source))$ python3 nonempty.py[] False[2, 3] True[2, 0] False[]True TrueThe final example uses an empty iterator. The object exists and is truthy, yet it yields no elements. The same guard therefore can't replace a check of an iterator's contents. If the data fits in memory, materialize it as a list before checking presence and values. This consumes the entire source and allocates memory.
Where does short-circuiting stop?
any stops at the first truthy element; all stops at the first falsy element. A generator expression computes tests on demand. A list comprehension computes all its tests before the function call starts.
def check(value): print("check", value) return value > 0
print(any(check(value) for value in [0, 2, 3]))print("list")print(any([check(value) for value in [0, 2, 3]]))$ python3 lazy.pycheck 0check 2Truelistcheck 0check 2check 3TrueThe first form never checks 3. In the second, all three calls to check have already happened when any receives the list. If an unreached step can raise an exception, the two forms may even behave differently. Don't put a required side effect inside a test that can be skipped.
What remains in an iterator after any?
The element that decides the result is consumed. The next iteration starts after it, rather than returning to the beginning.
source = iter([0, 2, 0])print(any(source))print(list(source))source = iter([0, 2, 0])print(any(source))print(all(source))print(all(source))$ python3 consumed.pyTrue[0]TrueFalseTrueOn the second source, any consumes 0 and then 2. The first all sees only the final 0, returns false, and exhausts the source. The second all receives an empty source and returns true.
Step 1 of 3
Before any
- consumed
- 0
- 00
- 12
- 20
No elements consumed.
Read all steps
1. Before any
- consumed
- 0
- 00
- 12
- 20
No elements consumed.
2. After any
- consumed
- 2
- 00consumed
- 12consumed
- 20
0 is falsy, 2 is truthy: any stops after 2.
3. After all
- consumed
- 3
- 00consumed
- 12consumed
- 20consumed
The final 0 is falsy: all consumes it and stops.
If you need to answer two questions about one list, pass the list again for each call. With a one-shot source, choose a suitable single pass or save its values. The same consumption issue appears with zip and unequal lengths.
Does any test a dictionary's values?
No. Iterating directly over a dictionary yields its keys. To test its values, call .values().
checks = {"ready": False, "valid": False}print(any(checks), all(checks))print(any(checks.values()), all(checks.values()))$ python3 keys.pyTrue TrueFalse FalseBoth key names are nonempty strings, even though their values are false. Write the predicate that matches your question before choosing any or all.
How does this apply to a palindrome?
Checking every symmetric pair works for palindrome comparisons. An empty string, like a one-character string, has no pairs to compare.
def same_pairs(text): return all(text[i] == text[-1 - i] for i in range(len(text) // 2))
for text in ("", "a", "abba", "abca"): print(repr(text), same_pairs(text))$ python3 pairs.py'' True'a' True'abba' True'abca' FalseThe exercise below adds a rule: no letters must mean a false result. Check that letters exist separately from checking matching pairs. Don't reject a single letter just because there are no pairs.
is_alpha_palindrome
Implement is_alpha_palindrome for ASCII input: ignore nonletters and letter case, then compare the letters. Return False when none remain; check empty text, punctuation alone, and a single letter.
Frequently asked questions
Do any and all return the element they found?
No. They return True or False. Retrieving an element requires a different loop or an appropriate search.
Does all check that a list is nonempty?
No. all([]) is True. For a nonempty list whose elements all pass a test, combine bool(values) with all.
Does a generator let me reuse the elements?
No. Calls advance through the same source. An element read by any or all is unavailable to the next iteration.
Why is all of a string spelling False true?
It iterates over nonempty characters, which are truthy. It doesn't interpret the text as the Boolean False.
Sources
