Ask about the whole collection with any and all
`any` is True when at least one item passes a test; `all` is True when every item does. Together they replace the flag-and-break loop.
- Write
any(test for item in items)andall(test for item in items) - Know the empty case:
any([])is False,all([])is True, and guard against it when that would be wrong - Combine
anyinsideallfor questions like *is every skill covered by someone?*
*Did any reading drop below freezing? Is every line of this order in stock?* With a loop you set a flag, test each item, and break once you know. any and all do exactly that.
Inside the call you can write a comprehension without square brackets: any(t < 0 for t in temps). That is a generator expression: it produces the test results one at a time, so any can stop at the first True, and all at the first False, without building a list.
Run each example to see what it prints. Running examples doesn't count toward progress.
temps = [6.7, 7.2, -2.1, 3.9] print(any(t < 0 for t in temps)) print(all(t < 10 for t in temps)) print(any([]), all([]))
That empty case is a real trap. An order with no lines would pass *every line is in stock* and get shipped as an empty box. Decide what an empty collection should mean, and check for it first.
def ready_to_ship(order): if not order["lines"]: return False return all(line["qty"] > 0 and line["in_stock"] for line in order["lines"]) full = {"lines": [{"qty": 2, "in_stock": True}, {"qty": 1, "in_stock": True}]} waiting = {"lines": [{"qty": 2, "in_stock": True}, {"qty": 1, "in_stock": False}]} empty = {"lines": []} print(ready_to_ship(full), ready_to_ship(waiting), ready_to_ship(empty))
any and all take one collection. Two separate values are a different question, answered with or and and.
order = {"paid": True, "shipped": False}
print(any(order["paid"], order["shipped"]))When to use it: validation (every field filled, any value negative), checks before an action, and coverage questions. Mistakes to avoid: forgetting that all of nothing is True; passing several values instead of one collection; and writing == True after the call: any(…) already is True or False.
any(test for x in xs): at least one passes.all(...): every one passes. Both stop as soon as the answer is known.any([])is False andall([])is True; guard the empty case when that is wrong for your problem.- Nest them for coverage questions:
all(any(...) for ...). - Next:
mapandfilter, and when a comprehension says the same thing more clearly.