any() in Python 2026: Check If Any Element Is True + Modern Patterns & Use Cases
The built-in any() function returns True if at least one element in an iterable is truthy (and False if the iterable is empty). It’s the logical counterpart to all() and remains one of the most elegant, short-circuiting, and performant tools for existence checks, early-exit conditions, and validation in Python code.
In 2026, with type hints, FastAPI route guards, data anomaly detection, ML early stopping, and async workflows, any() is more valuable than ever — especially in generator expressions and lazy evaluation. This March 23, 2026 update explains how any() behaves today, real-world patterns, performance notes, and best practices when combined with NumPy, JAX, asyncio, or plain Python.
TL;DR — Key Takeaways 2026
any(iterable)→Trueif any element is truthy,Falseif empty or all falsy- Short-circuits — stops at first truthy value (lazy & efficient)
- 2026 best practice: Use with generator expressions for lazy checks and memory efficiency
- Main use cases: existence checks, early-exit loops, validation, anomaly detection, ML stopping criteria
- Type-safe pattern:
any(isinstance(x, str) for x in lst) - Performance: C-optimized, extremely fast — ideal for large iterables
1. Basic Usage — Existence & Early Exit
print(any([False, False, True])) # True
print(any([0, "", None])) # False
print(any([])) # False (empty is False)
print(any([0, 0, 1])) # True
print(any(["", "data"])) # True
2. Real-World Patterns in 2026
Input Validation & Early Exit
def has_invalid_input(data: list) -> bool:
return any(not isinstance(x, (int, float)) for x in data)
print(has_invalid_input([1, 2.5, "oops"])) # True
ML Early Stopping / Anomaly Detection
import numpy as np
losses = [0.5, 0.4, 0.35, 0.6, 0.55]
# Any loss increased significantly? Early stop
if any(loss > prev_loss * 1.5 for prev_loss, loss in zip(losses, losses[1:])):
print("Early stopping triggered")
Async Existence Check (asyncio 2026)
async def any_task_failed(tasks):
results = await asyncio.gather(*tasks, return_exceptions=True)
return any(isinstance(r, Exception) for r in results)
3. any() vs all() vs Alternatives – Comparison 2026
| Function | Returns True When | Empty Iterable | Short-circuits? | Best For |
|---|---|---|---|---|
| any() | At least one truthy | False | Yes (first truthy) | “Any item satisfies condition” |
| all() | Every element truthy | True | Yes (first falsy) | “All items satisfy condition” |
| any(x > 0 for x in lst) | Lazy generator | False | Yes | Memory-efficient checks |
| not all(x <= 0 for x in lst) | Equivalent to any(x > 0 ...) | False | Yes | Readability trade-off |
4. Best Practices & Performance in 2026
- Use generator expressions —
any(x > 0 for x in lst)— lazy, memory-safe - Type hints 2026:
from typing import Iterable, TypeVar T = TypeVar("T") def has_positive(it: Iterable[T]) -> bool: return any(x > 0 for x in it) - Performance: any() is C-optimized and short-circuits — stops at first truthy value
- Avoid: Converting to list first — wastes memory on large iterables
- Free-threading (3.14+): Safe concurrent iteration in generators
Worked Example: Finding What Matched
any() answers "is there at least one?" and stops at the first truthy result. Often you also want to know which item matched; next() with a default gives you that with the same short-circuit behaviour.
banned = ("password", "secret", "token")
log_lines = [
"user login ok",
"config loaded: token=abc123",
"request served",
]
leaks = any(word in line for line in log_lines for word in banned)
print(leaks) # True
first = next((line for line in log_lines
if any(word in line for word in banned)), None)
print(first) # config loaded: token=abc123
print(any(x > 100 for x in [])) # False - empty input
print(next((x for x in [] if x > 100), "none found")) # none found
Common Mistakes
- Writing
any(x == 0 for x in data)when0 in datais clearer - Expecting
any()to return the matching item: it returns onlyTrueorFalse - Passing a list comprehension, which evaluates every element before
any()starts - Checking a DataFrame column with built-in
any(): useseries.any()
Quick Summary
any()isTrueif at least one item is truthy,Falsefor empty input- Combine with
next()to get the first match - Use generators to keep the early exit
Conclusion — any() in 2026: Simple, Fast, Essential
any() is tiny but incredibly powerful — it turns complex “at least one item satisfies X” logic into one readable line. In 2026, use it with generator expressions, type hints, and short-circuiting behavior for clean, efficient, and safe code — especially in validation, early-exit loops, anomaly detection, and async workflows. Pair it with all() for complete logical coverage.
Next steps:
- Replace any manual loop with any() or all() in your next condition check