any() short-circuits: it scans the iterable and returns True the moment it finds a truthy element, without evaluating the rest, which matters if you pass it a generator expression that's expensive to compute. On an empty iterable, any() returns False, matching the intuition that 'at least one is true' can't hold if there's nothing to check.
1Understanding any()
any() short-circuits: it scans the iterable and returns True the moment it finds a truthy element, without evaluating the rest, which matters if you pass it a generator expression that's expensive to compute. On an empty iterable, any() returns False, matching the intuition that 'at least one is true' can't hold if there's nothing to check.
Pass a generator expression, not a list comprehension, to any() — it lets any() short-circuit without first building the whole list in memory.
ages = [12, 15, 8, 20]
has_adult = any(age >= 18 for age in ages)
print(has_adult)2Practical Example
Here is a real-world application of any() showing how it is used in production Python code.
errors = []
if any(errors):
print("Something went wrong")
else:
print("All checks passed")3Best Practices
Follow these guidelines when working with any():
1. Use any() with a generator expression instead of a manual loop with a flag variable and break
2. Prefer a generator expression over a list comprehension inside any()/all() so short-circuiting actually saves work
3. Remember any() on an empty iterable is False — check for that edge case if an empty input is possible
Tip: Pass a generator expression, not a list comprehension, to any() — it lets any() short-circuit without first building the whole list in memory.
ages = [12, 15, 8, 20]
has_adult = any(age >= 18 for age in ages)
print(has_adult)