any And all Short-Circuit Generator Checks
any stops at the first truthy item and all at the first falsy one, empty inputs default to False and True, and next() finds the decisive item itself.
Code
# any / all 都是短路求值:结论确定就停止消费迭代器
def probe(n):
print(" probing", n)
return n > 0
print("any([1,-2,3]):")
print(any(probe(n) for n in [1, -2, 3])) # 命中 1 即停
print("all([1,-2,3]):")
print(all(probe(n) for n in [1, -2, 3])) # 撞上 -2 即停
print("all([]) =", all([]), "| any([]) =", any([])) # 空值: all 真, any 假
# 生成器表达式直接在调用里写条件,不必先建列表
orders = [{"total": 0}, {"total": 40}, {"total": 120}]
print("has paid order :", any(o["total"] > 0 for o in orders))
print("all orders paid :", all(o["total"] > 0 for o in orders))
# 想知道"是哪一条"而不是"有没有",用 next + 默认值
first = next((o for o in orders if o["total"] > 0), None)
print("first paid order:", first)Output
Captured from a sandboxed run of this snippet in the build pipeline.
any([1,-2,3]):
probing 1
True
all([1,-2,3]):
probing 1
probing -2
False
all([]) = True | any([]) = False
has paid order : True
all orders paid : False
first paid order: {'total': 40}How it works
The snippet is organized around the function probe.
What to watch for
- No external packages — everything relies on the language’s built-in APIs.
Using it
Signature: def probe(n)
Running the file prints labeled results such as probing, any([1,-2,3]):, all([1,-2,3]): — each operation’s effect is visible in the output.
probe is the public entry point; everything else in the file exists to support it.
Key statements
def probe(n):
print(" probing", n)
return n > 0
Interactive Tools for This Topic
FAQ
- Is the dependency story complicated?
- Not at all: zero dependencies, so there is nothing to version or audit. The file defines `probe` at load time.
Report a problem with this exampleOpens a pre-filled issue on GitHub.