any and all
🌍 In real life. A teacher asks two different questions about a class's homework: "Did anyone forget it?" and "Did everyone hand it in?" For the first, the moment she finds one missing book she can stop looking. For the second, the moment she finds one missing book she also knows the answer: no.
Python's any and all ask exactly these two questions.
The idea in one sentence: any(items) is True if at least one item counts as True, and all(items) is True only if every item does; both stop as soon as they know.
Its words:
any(...): "is there at least one?"all(...): "is every one?"- generator expression: a comprehension without its square brackets,
n < 0 for n in nums, which makes one value at a time - short-circuit: stopping early once the answer is known
Step by step, for any(n < 0 for n in [3, -1, 5]):
3 < 0is False, so keep looking.-1 < 0is True, so the answer is True.- Python stops: 5 is never even checked.
nums = [3, -1, 5]
negatives = [n for n in nums if n < 0]
print(negatives)
print(any([n < 0 for n in nums]))
print(all([n > 0 for n in nums]))When the comprehension is the only thing inside the call, you can leave out its square brackets. Python then checks one item at a time and stops as soon as it knows the answer.
nums = [3, -1, 5]
print(any(n < 0 for n in nums))
print(all(n > 0 for n in nums))
words = ["tea", "toast", "tart"]
print(all(w.startswith("t") for w in words))With nothing to check, all([]) is True (no item breaks the rule) and any([]) is False (no item passes).
print(all([]), any([]))
def describe(nums):
if all(n % 2 == 0 for n in nums):
return "all even"
if any(n % 2 == 0 for n in nums):
return "some even"
return "no even"
print(describe([2, 4]))
print(describe([1, 2]))
print(describe([1, 3]))What it costs. In the worst case each walks the whole list once, but they often finish early. With the square brackets left out, nothing is built in advance either: any(n < 0 for n in nums) checks one number at a time, while any([n < 0 for n in nums]) first builds the whole list of True/False values, then looks at it.
Mistakes and edge cases.
- any where you meant all. "Did every mark pass?" needs
all;anysays True as soon as one passes (see the bug question). - Empty inputs.
all([])is True andany([])is False, which can surprise you; check for an empty list when it matters. - Passing a condition instead of a sequence.
all(nums > 0)compares a list with 0 and fails with a TypeError; writeall(n > 0 for n in nums). - Values, not just True/False.
all([0, 1])is False because 0 counts as False.
Quiz
What does this print?
print(any([False, False, True]))What does this print?
print(all(n > 0 for n in [1, 2, 0]))What does this print?
print(all([]), any([]))What does this print?
print(any(len(w) > 3 for w in ["hi", "tea"]))Which checks that every name in
namesstarts with a capital letter?- all(n[0].isupper() for n in names)
- any(n[0].isupper() for n in names)
- names[0].isupper()
This should say whether every mark is a pass (33 or more). It prints True, though 25 fails. Which line has the mistake?
marks = [40, 25, 70] passed_all = any(m >= 33 for m in marks) print(passed_all)
Coding tasks
Write
has_negative(nums)that returnsTrueif any number is below 0.Write
all_passed(scores)that returnsTrueif every score is at least 40 (andTruefor no scores at all).Write
average_middle(salaries)that returns the average salary, leaving out the smallest and the largest. There are at least 3 salaries, all different.