Using Python any() with a Generator
Learn how Python's any() works with generator expressions, including short-circuit behavior, memory efficiency, and practical use cases.

When you call any() with a generator expression, Python evaluates the iterable lazily and stops at the first truthy value. This gives you short-circuit behavior without building an intermediate list. For example:
values = [0, 0, 1, 0]
result = any(v > 0 for v in values)
print(result) # TrueThe generator expression (v > 0 for v in values) produces values one at a time. any() consumes them in order and returns True as soon as it sees the first truthy value, without checking the remaining elements. The return value is the same as it would be with a list comprehension, but the generator avoids allocating a full list of booleans first.
How any() Consumes a Generator
any() is a built-in function that takes an iterable and returns True if any element is truthy. When the iterable is a generator, Python pulls elements from it using next() internally. The function does not know or care whether the iterable is a generator, a list, a tuple, or a custom iterator. The difference is purely in how the elements are produced.
A generator expression is defined with parentheses, not square brackets. The syntax (expr for item in iterable) creates a generator object. Passing that object to any() triggers iteration. Because generators are lazy, each element is computed only when requested. This matters when the expression itself has side effects or is expensive to compute.
# Generator expression - lazy
any(expensive(x) for x in data)
# List comprehension - eager
any([expensive(x) for x in data])In the first case, expensive(x) runs only until a truthy result appears. In the second case, the list comprehension computes expensive(x) for every element before any() even starts checking. The generator version can save significant work when the first truthy value appears early in the sequence.
Short-Circuit Evaluation and Early Exit
The main advantage of combining any() with a generator is early termination. As soon as a truthy value is found, any() stops iterating. This is how any() works: it loops over the iterable and returns immediately when it encounters a truthy element.
Consider a check that scans a large file for a specific pattern:
def contains_error(lines):
return any("ERROR" in line for line in lines)If the first line already contains ERROR, the generator yields True and any() returns immediately. The rest of the file is never read. This is not just a performance nicety; it changes the behavior of code that depends on side effects. For instance, if the generator expression calls a function that increments a counter, the counter stops incrementing once any() returns.
count = 0
def check(x):
global count
count += 1
return x > 5
any(check(i) for i in range(10))
print(count) # 7, because 6 is the first truthy valueHere check() is called for values 0 through 6, then any() stops. The count is 7, not 10. Understanding this early exit is essential when using generator expressions with side effects, even if side effects in a generator are generally discouraged.
Memory Efficiency: Generator vs List
Passing a list comprehension to any() forces Python to build the entire list of booleans in memory before any evaluation. For large datasets, this can be wasteful. A generator expression avoids that allocation entirely.
# List comprehension - builds full list
any([x % 2 == 0 for x in range(1_000_000)])
# Generator expression - lazy, memory-friendly
any(x % 2 == 0 for x in range(1_000_000))The list version creates a list with a million booleans, using roughly 8 MB of memory on a 64-bit CPython build (plus overhead). The generator version holds only one boolean at a time. In most cases, the generator is the better choice for large or infinite iterables. If you already have a list, iterating it with any() avoids per-item generator overhead and may be faster than a generator, but building a list just to pass to any() usually costs more than it saves. For a one-off check, the generator is usually preferred.
Common Patterns and Realistic Examples
Checking Multiple Conditions
A common use is validating that at least one condition holds across a collection of objects.
users = [
{"name": "alice", "active": False},
{"name": "bob", "active": True},
{"name": "carol", "active": False},
]
has_active = any(user["active"] for user in users)This is concise and reads well. The generator expression keeps the logic inline without requiring a separate loop.
Exiting Early from a Search
When searching for a matching element, any() can replace a manual loop with a break.
# Manual loop
found = False
for item in items:
if predicate(item):
found = True
break
# Generator + any
found = any(predicate(item) for item in items)The any() version is shorter and clearly expresses intent. It also works with infinite iterators, as long as the predicate eventually returns True.
from itertools import count
first_even = any(i % 2 == 0 for i in count(1)) # True after checking 1 and 2Combining with File or Stream Reading
Generators are natural for processing streams. any() can check if a stream contains a marker without reading the entire stream.
def stream_has_marker(stream, marker):
return any(line.strip() == marker for line in stream)Because the generator pulls lines lazily, the function stops reading as soon as the marker is found. This is particularly useful for large logs or network streams.
Performance Considerations and When to Avoid Generators
While generators save memory, they are not always faster. Each next() call on a generator has some overhead compared with iterating over an existing list. For small sequences, the difference is negligible. For large sequences where the first truthy value appears late, the per-item generator overhead can make a generator slower than iterating a pre-built list; however, building that list eagerly has its own cost. The memory savings usually outweigh the speed difference, especially when the sequence is huge.
There is also a subtle behavior with any() and an empty generator. If the generator produces no elements, any() returns False. This is consistent with the existential quantifier: no element is truthy.
any(x for x in []) # FalseIf you need to distinguish between "no elements" and "all elements are falsy", any() cannot do that. You would need to check the iterable separately, but that often defeats the purpose of using a generator.
Another consideration is that any() does not accept a second argument. There is no way to provide a default value for an empty iterable; if you need a fallback, you must handle it manually. This is rarely a problem because False is usually the correct result for an empty set.
Edge Cases and Pitfalls
Generator Exceptions
If the generator raises an exception during iteration, any() propagates it. This is expected but can be surprising if the generator expression contains a function that may fail.
def risky(x):
if x == 3:
raise ValueError("bad")
return x > 0
any(risky(x) for x in range(5)) # raises ValueErrorYou should handle exceptions around the any() call if the generator can raise. This is no different from any other iterable, but the lazy evaluation means the exception may occur after several elements have already been processed.
Side Effects in Generator Expressions
Because generators are lazy, side effects happen only as elements are consumed. This can lead to non-obvious ordering. For example, if you use any() with a generator that prints something, the printing stops when any() returns.
def emit(x):
print(f"checking {x}")
return x > 3
any(emit(x) for x in range(5))
# prints checking 0 through checking 4, then stopsThis is often desirable, but if you expect all elements to be processed, you must use a list comprehension or a loop instead.
Infinite Generators
any() can be used with infinite generators, but only if the condition is eventually met. If the condition is never true, the function will loop forever. This is a common source of hangs.
# Dangerous: this predicate is never true, so this never terminates
any(x == -1 for x in count())Always ensure there is a termination condition when using infinite iterators with any().
Alternative Approaches: any() vs all() and Manual Loops
all() is the counterpart of any(). It returns True only if every element is truthy. Like any(), it stops at the first falsy value. The same generator-expression pattern applies.
all(x > 0 for x in values)Choosing between any() and all() depends on whether you need at least one match or every match. A manual loop gives you more control, such as capturing the matching element itself. any() only returns a boolean; it does not tell you which element matched. If you need the value, use a for loop with break or use next() with a generator.
# Get the first matching value
first_match = next((x for x in items if predicate(x)), None)This pattern is often more useful than any() when you need the actual item. any() is best when you only care about existence. For a quick existence check, any() with a generator is idiomatic and efficient. For more complex logic, a manual loop may be clearer.
The decision between any() and a manual loop often comes down to readability. If the condition is simple and you only need a boolean, any() is more concise. If you need to perform additional actions after finding a match, a loop is more explicit. In most production code, any() with a generator expression is the preferred way to express "is there at least one?" because it is both readable and memory-efficient.
Try matching browser tools
All toolsSmall utilities that fit Python work — they run entirely in this browser tab, so nothing you paste leaves your device.
Related Python guides
All Python guidesPython iter(): How the Built-in Function Works
Explains Python's iter() built-in: how it creates iterators, the two-argument sentinel form, custom iterator classes, and common edge cases.
Python Pika: Queues, Exchanges, Routing Keys, and Acknowledgements
Learn how to use Python's Pika client with RabbitMQ: declare queues and exchanges, publish with routing keys, consume messages, and handle acknowledgements reliably.
Python Kafka: kafka-python vs Confluent Client
python kafka python vs confluent kafka: Compare kafka-python and Confluent Kafka Python clients: API differences, performance, feature coverage, and when to choose eac...
Python Kafka Offsets, Partitions, and Manual Commits
Learn how Kafka offsets and partitions work and how to manually commit offsets in Python consumers with kafka-python and confluent-kafka. Covers sync vs async commits, rebalances, and seeking.
More in Python
All Python guidesThe guides filed next to this one in Python, in library order.