Sub topic 11
any() and all()
This chapter covers any() and all(), the two built-ins that reduce a whole iterable of values to a single bool. It assumes you know truthiness, and/or/not, short-circuiting, and generator expressions at a basic level. The earlier chapters on those topics cover the rest.
What they do
any(iterable) returns True if at least one item is truthy. all(iterable) returns True if every item is truthy. Both use the same truth value testing rules as an if statement, so 0, "", None, and empty containers count as false.
print(any([0, "", None])) # False
print(any([0, "", None, 1])) # True
print(all([1, "a", [0]])) # True
print(all([1, "a", []])) # FalseThe list [0] in the third line is truthy because it is a non-empty list. any and all look only at the truth value of each item, not at what the item contains.
You can think of them as loops with an early exit. These two functions behave the same as the built-ins:
def my_any(iterable):
for item in iterable:
if item:
return True
return False
def my_all(iterable):
for item in iterable:
if not item:
return False
return True
print(my_any([0, 3]), my_all([0, 3])) # True Falseany is like a chain of or, and all is like a chain of and. The difference is that the operators accept a fixed number of operands written in the source, while the functions accept an iterable of any length.
Empty iterables
The empty case is the most common source of confusion.
print(any([]), all([])) # False Trueany([]) is False because there is no item that is truthy. all([]) is True because there is no item that is falsy. Logicians call the second result vacuous truth. It matches the loop version above: with no items, the for body never runs and the function reaches its final return.
This is usually what you want, but it can hide bugs. Suppose you check that every order in a list has been paid:
orders = []
if all(order["paid"] for order in orders):
print("ready to ship") # runs, even though there are no ordersIf an empty list should be an error or a no-op, test for that separately, for example with if orders and all(...).
They return a bool, not an operand
or and and return one of their operands. any and all always return exactly True or False.
print(0 or "default") # default
print(any([0, "default"])) # True
print("a" and "b") # b
print(all(["a", "b"])) # TrueIf you want the first truthy value, use or or next(). Don't use any:
values = [0, "", "first", "second"]
print(next((v for v in values if v), None)) # firstShort-circuiting and generators
any stops at the first truthy item. all stops at the first falsy item. The short-circuit only helps when the items are produced lazily, which is what a generator expression does. The next example prints each value as it is checked.
def noisy(values):
for v in values:
print("checking", v)
yield v
print(any(noisy([0, 5, 9])))
print(all(noisy([3, 0, 9])))The output is:
checking 0
checking 5
True
checking 3
checking 0
FalseThe value 9 is never examined in either call.
Generator expression versus list comprehension
Square brackets build the whole list before any or all sees it, so nothing is skipped. Without brackets you pass a generator expression, which produces one item at a time.
def check(n):
print("check", n)
return n > 1
print(any([check(n) for n in [1, 2, 3]])) # calls check 3 times
print(any(check(n) for n in [1, 2, 3])) # calls check 2 timesThe first line prints check 1, check 2, check 3, then True. The second prints check 1, check 2, then True. When check is slow, has side effects, or the input is large or infinite, drop the brackets.
all is the mirror image. It returns False at the first falsy item and returns True when the items run out.
The common pattern: a condition on each item
Most real uses pair any or all with a generator expression that turns each item into a boolean.
nums = [1, 2, 3]
print(any(n > 2 for n in nums)) # True
print(all(n > 0 for n in nums)) # True
text = "the quick brown fox"
print(any(w in text for w in ["cat", "fox"])) # True
print(all(w in text for w in ["quick", "fox"])) # TrueHere w in text is a substring test on a string. "he" in text would also be True. If you mean whole words, split the text first with text.split().
Two other idioms come up often:
any(x is None for x in items)asks whether the list contains a missing value.all(x is not None for x in items)asks whether every value is present.
The second form matters because plain all(items) tests truthiness, not presence:
items = [0, "", False]
print(all(items)) # False
print(all(x is not None for x in items)) # TrueUse an explicit is not None test whenever 0, "", or False are valid values. This is the same falsy-versus-None distinction from the earlier chapters on None checks.
What gets iterated
any and all accept any iterable, and what they see depends on what you pass.
d = {"a": 0, "b": 0}
print(any(d)) # True (iterates the keys "a" and "b")
print(any(d.values())) # False (iterates the values 0 and 0)
print(all("abc")) # True (each character is a non-empty string)
print(any("")) # FalseA dict iterates over its keys, so any(d) checks the keys, not the values. Pass d.values() or d.items() when you mean something else. Note that d.items() yields tuples such as ("a", 0), which are always truthy because they are non-empty.
Iterators are consumed
If you pass an iterator, any and all use it up as far as they read.
it = iter([0, 0, 1, 2])
print(any(it)) # True
print(list(it)) # [2]any read 0, 0, and 1, stopped, and left 2 unread. Do not reuse an iterator after testing it, and do not pass the same generator to two checks.
Relating any, all, and not
The two functions are related by De Morgan's laws:
not any(cond(x) for x in xs)is the same asall(not cond(x) for x in xs).not all(cond(x) for x in xs)is the same asany(not cond(x) for x in xs).
In practice this lets you pick the form that reads best:
values = [1, 2, 3]
print(not any(v < 0 for v in values)) # True
print(all(v >= 0 for v in values)) # TrueThe two lines agree here, but the rewrite from not (v < 0) to v >= 0 is not always valid. NaN breaks it, as the chapter on pitfalls described, because every ordering comparison with NaN is False:
nan = float("nan")
print(not any(v < 0 for v in [nan])) # True
print(all(v >= 0 for v in [nan])) # FalseWhen NaN is possible, keep the not form that states what you actually want to rule out.
Summary of behaviors
| Call | Result | Reason |
|---|---|---|
| `any([])` | `False` | No item is truthy |
| `all([])` | `True` | No item is falsy |
| `any([0, None])` | `False` | Both items are falsy |
| `all([1, "x", [0]])` | `True` | Each item is truthy, including the non-empty list |
| `any(["False"])` | `True` | A non-empty string is truthy |
| `any({"a": 0})` | `True` | Iterates the key `"a"` |
| `any({"a": 0}.values())` | `False` | Iterates the value `0` |
Common errors
- Passing a comparison instead of an iterable.
any(nums > 2)compares a list with an int and raisesTypeError. Writeany(n > 2 for n in nums). - Forgetting that
all([])isTrue. Guard against empty input when emptiness should fail the check. - Testing truthiness when you mean
None.all(values)fails on a legitimate0. Useis not None. - Building a list when a generator would do.
any([f(x) for x in xs])callsfon every item and uses memory for the list. Remove the brackets. - Reusing a consumed iterator. A generator or
iter(...)object keeps its position afteranyorallreturns. - Expecting the matching item back. Both functions return only a
bool. Usenext(...)with a default to retrieve the item.
Exercise
What do any([]), all([]), and all(x is not None for x in [0, "", False]) print, and why?
Show answer
They print False, True, and True. any([]) is False because no item is truthy. all([]) is True because no item is falsy, so the condition holds vacuously. In the third call, each item is tested with is not None. The values 0, "", and False are all falsy but none of them is None, so every test is True.
Exercise
The call any(check(n) for n in [1, 2, 3, 4]) uses a function check that returns True only for n == 2. How many times is check called? How many times would it be called if you wrote any([check(n) for n in [1, 2, 3, 4]])?
Show answer
The generator version calls check twice, for 1 and 2, and then stops because 2 gives True. The list comprehension version calls check four times, because it builds the whole list before any sees it.
Exercise
A dict settings = {"debug": False, "verbose": False} is given. Write one expression that is True if any setting is switched on, and say what any(settings) returns instead.
Show answer
Use any(settings.values()), which is False here. any(settings) returns True because it iterates the keys "debug" and "verbose", which are non-empty strings and therefore truthy.