Python 3D Academyবাংলা

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]):

  1. 3 < 0 is False, so keep looking.
  2. -1 < 0 is True, so the answer is True.
  3. 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; any says True as soon as one passes (see the bug question).
  • Empty inputs. all([]) is True and any([]) 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; write all(n > 0 for n in nums).
  • Values, not just True/False. all([0, 1]) is False because 0 counts as False.

Quiz

  1. What does this print?

    print(any([False, False, True]))
  2. What does this print?

    print(all(n > 0 for n in [1, 2, 0]))
  3. What does this print?

    print(all([]), any([]))
  4. What does this print?

    print(any(len(w) > 3 for w in ["hi", "tea"]))
  5. Which checks that every name in names starts with a capital letter?

    • all(n[0].isupper() for n in names)
    • any(n[0].isupper() for n in names)
    • names[0].isupper()
  6. 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

  1. Write has_negative(nums) that returns True if any number is below 0.

  2. Write all_passed(scores) that returns True if every score is at least 40 (and True for no scores at all).

  3. Write average_middle(salaries) that returns the average salary, leaving out the smallest and the largest. There are at least 3 salaries, all different.