Sub topic 11
any() and all()
This chapter assumes you know truthiness, comparison operators, and how and and or short-circuit. It also assumes you can write a generator expression such as (n > 2 for n in nums).
What they do
any() and all() are built-in functions that reduce an iterable of values to one bool.
any(iterable)returnsTrueif at least one item is truthy.all(iterable)returnsTrueif every item is truthy.
Both apply the normal truthiness rules to each item, so the items do not need to be booleans.
print(any([]), all([])) # False True
print(any(n > 2 for n in [1, 2, 3])) # True
print(all(n > 0 for n in [1, 2, 3])) # True
print(any(["", 0, None])) # False
print(all(["a", 1, [0]])) # TrueThe last line is True because [0] is a non-empty list, and non-empty lists are truthy whatever they contain.
Think of them as chained or and and
any(xs) behaves like x1 or x2 or x3 .... all(xs) behaves like x1 and x2 and x3 .... The difference is that the functions always return a plain True or False, while or and and return one of their operands.
values = ["", "fallback"]
print(values[0] or values[1]) # fallback
print(any(values)) # TrueUse or when you want the value itself, such as a default. Use any() when you want a yes or no answer, especially over a collection of unknown length.
Short-circuiting
Like or and and, the two functions stop as soon as the answer is known:
any()stops at the first truthy item.all()stops at the first falsy item.
This only saves work if the items are produced lazily. A generator expression produces items one at a time. A list comprehension builds the whole list first.
def check(n):
print("checking", n)
return n > 1
print(any(check(n) for n in [1, 2, 3]))
# checking 1
# checking 2
# True
print(any([check(n) for n in [1, 2, 3]]))
# checking 1
# checking 2
# checking 3
# TrueThe generator version never examines 3. The list version calls check on every item before any() sees the list. For large or expensive inputs, prefer the generator form.
Empty iterables
The empty case follows from the definitions:
| Call | Result | Reason |
|---|---|---|
| `any([])` | `False` | No item is truthy. |
| `all([])` | `True` | No item is falsy, so nothing breaks the rule. |
Logicians call the second case vacuous truth. It is a common source of bugs.
scores = []
print(all(s >= 50 for s in scores)) # True, even though there are no scores
if scores and all(s >= 50 for s in scores):
print("everyone passed")
else:
print("nobody to evaluate") # nobody to evaluateIf an empty collection should count as a failure, test for it explicitly.
Common errors
- Passing a non-iterable.
any(5)andany(None)raiseTypeError. A function that may returnNoneinstead of a list needs a guard, for exampleany(result or []). - Iterating a dict.
any(d)tests the keys, not the values. Useany(d.values())when you mean the values. - Passing several arguments.
any(a, b)raisesTypeErrorbecause the function takes exactly one iterable. Writeany([a, b]). - Confusing falsy with missing.
all([0, 1])isFalsebecause0is falsy. To test only forNone, writeall(x is not None for x in items). - Using any() for membership.
any(x == target for x in items)works, buttarget in itemsis shorter and clearer.
readings = [3, 0, 7, None]
print(all(readings[:3])) # False, because 0 is falsy
print(all(r is not None for r in readings[:3])) # True
print(all(r is not None for r in readings)) # FalseExercise
What do all([]), any([]), and all(x > 0 for x in []) return, and how would you make a check "every score is at least 50" fail when the list of scores is empty?
Show answer
all([]) returns True, any([]) returns False, and all(x > 0 for x in []) returns True because an empty iterable has no falsy item. To make the check fail on an empty list, test for content first: if scores and all(s >= 50 for s in scores):.
Exercise
Given words = ["", "py", "bool"], what do any(words), all(words), and all(w for w in words if w) return?
Show answer
any(words) is True because "py" is truthy. all(words) is False because "" is falsy. all(w for w in words if w) is True because the filter removes the empty string, so only truthy items reach all().