Python any(): Truth Tests, Short-Circuiting, and Generators

Quick answer: any() is Python’s existential test: it returns True as soon as one item is truthy and False for an empty iterable or one whose items are all false. A generator lets it stop without materializing every result.

Python any infographic showing iterable truth checks, short-circuit evaluation, empty input, and generator expressions
any() stops at the first truthy item, so a generator can avoid building or evaluating the rest of a large input.

Python any() is a built-in function that returns True when at least one item in an iterable is truthy. If every item is falsey, or if the iterable is empty, it returns False.

The official Python documentation for any() defines the function and shows its equivalent loop. The truth value testing documentation explains which objects count as true or false.

Use any() for yes-or-no questions across a group: Does any score pass? Does any row have an error? Does any file name match a suffix? It is clearer than writing a manual loop when the only answer you need is whether at least one match exists.

any() short-circuits. That means it stops as soon as it finds a truthy item. With generator expressions, this can save work because Python does not need to inspect the rest of the input after the answer is known.

The function does not tell you which item matched or how many items matched. If you need the first matching item, use a loop or next(). If you need a count, use sum() with a boolean expression.

Think of any() as a question about existence. It answers “does at least one item pass?” It does not validate that every item passes; that job belongs to all(). Keeping those two questions separate makes conditions easier to read.

Because any() accepts any iterable, it works with lists, tuples, sets, dictionaries, files, generator expressions, and custom iterable objects. With dictionaries, iteration checks keys unless you explicitly use .values() or .items().

Basic any Usage

Pass an iterable of values to any().

values = [0, "", None, "ready"]

print(any(values))
print(any([0, "", None]))
print(any([]))

The first list returns True because "ready" is truthy. The second and third return False.

Remember that any([]) is False. There is no item that proves the condition true.

If an empty iterable should be treated as invalid input, check for that before calling any(). The built-in returns a logical answer, not a data-quality warning.

Use A Generator Expression

The most common pattern is any(condition for item in items).

scores = [72, 81, 95, 64]

has_high_score = any(score >= 90 for score in scores)

print(has_high_score)

This reads as “is there any score at least 90?” The generator produces boolean results one at a time.

Use this shape instead of building a temporary list unless you specifically need that list for another reason.

A generator expression also keeps side effects out of the check. Prefer a simple condition inside any(); if the expression starts doing logging, mutation, or network work, a normal loop is usually clearer.

Python Pool infographic showing Python any, iterable values, truthiness, and boolean results
Input iterable: Python any, iterable values, truthiness, and boolean results.

Check Strings Or Names

any() pairs well with membership tests and string methods.

names = ["ada.py", "notes.txt", "report.md"]
suffixes = (".py", ".ipynb")

has_python_file = any(name.endswith(suffixes) for name in names)

print(has_python_file)

The endswith() call accepts a tuple of suffixes, so each name is checked against both accepted endings.

For large directory scans, this kind of generator expression avoids extra storage and can stop early after the first match.

When checking text, be explicit about case rules. Normalize with casefold() first if capitalization should not matter, or leave the text untouched when case-sensitive matching is the correct behavior.

Understand Truthy Values

any() uses normal Python truth testing for each item.

groups = [[], [], [1, 2]]
flags = [False, 0, "yes"]

print(any(groups))
print(any(flags))

Empty lists are falsey, while a non-empty list is truthy. Empty strings, zero, None, and False are also falsey.

If that implicit truth rule is too subtle, write an explicit condition inside the generator expression.

For example, any(groups) asks whether any group is non-empty. any(len(group) > 2 for group in groups) asks a different, clearer question about group size.

Python Pool infographic mapping any through elements until the first truthy value stops iteration
Short-circuit: Any through elements until the first truthy value stops iteration.

See Short Circuiting

any() stops after the first truthy result.

def checks():
    for item in [0, "", "match", "unused"]:
        print("checking", repr(item))
        yield item

print(any(checks()))

The final item is never checked because "match" already made the answer True.

This behavior is useful when each check is expensive, but keep generator expressions readable so the short-circuit rule is easy to understand.

Short-circuiting also means later items may never be evaluated. Do not put required cleanup or required side effects inside a generator expression passed to any().

Python Pool infographic comparing list input with generator expression, laziness, and side effects
Generator input: List input with generator expression, laziness, and side effects.

Use any Instead Of A Manual Flag

A manual loop can be replaced when it only sets a boolean flag.

numbers = [3, 7, 10, 13]

has_even = any(number % 2 == 0 for number in numbers)

print(has_even)

This is shorter than initializing a flag, looping, setting it, and breaking. Use the manual loop when you need the matching value, logging, or extra side effects.

Choose the tool by the result you need: any() for one boolean, all() when every item must pass, sum() for counts, and next() when the first matching item itself is needed.

In short, use any() when you need to know whether at least one item passes a truth test. Use a generator expression for conditions, keep empty-input behavior in mind, and switch to next(), sum(), or a loop when you need more than a boolean answer.

Use A Predicate With A Generator

The useful pattern is any(predicate(item) for item in items). The generator produces one Boolean at a time, and any() stops at the first True. This keeps the code readable and avoids building an intermediate list.

records = [{"status": "queued"}, {"status": "ready"}, {"status": "done"}]
has_ready = any(record["status"] == "ready" for record in records)
print(has_ready)
Python Pool infographic testing empty iterables, zero, None, custom truth, and validation
Truth checks: Empty iterables, zero, None, custom truth, and validation.

Short-Circuiting Is Observable

Because any() stops early, later generator expressions may never run. That is normally a performance benefit, but do not put required side effects inside the predicate. Separate side effects from the truth test when every item must be visited.

def is_positive(value):
    print("checking", value)
    return value > 0

print(any(is_positive(value) for value in [-2, 0, 4, 8]))

Choose The Right Test

Use in for direct membership, any() when a predicate must be applied, and all() when every item must pass. Remember that any([]) is False and any([0, “”, None]) is also False because those values are falsey.

values = [0, "", None, 3]
print(any(values))
print(any(value is None for value in values))
print(all(value is not None for value in values))

See the built-in function definitions for any() and all() when choosing a truth-test API.

For related membership checks, compare NumPy any(), finding a string in a list, and finding a list index.

Frequently Asked Questions

What does any() do in Python?

any() returns True when at least one item in an iterable is truthy; it returns False when every item is false or the iterable is empty.

Does Python any() short-circuit?

Yes. It stops as soon as it finds a truthy value, which makes generator expressions useful for large or expensive checks.

What is the difference between any() and all()?

any() asks whether at least one item is truthy, while all() asks whether every item is truthy.

Should I use any() or the in operator?

Use in for direct membership in a container; use any() when each candidate needs a predicate or transformation before it can be tested.

Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted