any() and all()
any() tells you if at least one item is true; all() tells you if every item is true.
Used in 36 lessons of the course, from 00.04.
Both functions take an iterable (a list, a generator, anything you can loop over with for) and return a single True or False.
any(items)isTrueif at least one item is true.all(items)isTrueif every item is true.
The usual pattern is to pass a generator expression with a condition, like any(n.startswith("DEMO_") for n in os.environ). Read it as: "does any name start with DEMO_?". You don't build a whole list, and they stop as soon as the answer is known.
Two empty cases are worth remembering: any([]) is False and all([]) is True. Nothing exists to contradict all.
In the course you'll see not any(...) to confirm something is gone, like the demo variables in the environment.
Reach for it when: you need a yes-or-no answer about a whole collection: does any item match, or do all of them?
Examples
Common mistake
words = ["apple", "banana"]
print(any("a" in w for w in words) == "True")
print(all([]))Why: any returns the boolean True, not the string "True", so the comparison is False. Also, all of an empty collection is True, which surprises people.
How to write it: Use the result directly (if any(...):) and check for an empty collection when that matters.
