How to use any() in Python

Learn how to use Python's any() function with examples, tips, real-world applications, and common error debugging. Master this powerful tool.

How to use any() in Python
Published on: 
Wed
Mar 25, 2026
Updated on: 
Thu
Mar 26, 2026
The Replit Team

Python's any() function is a powerful tool to check if at least one element in an iterable is true. It simplifies conditional logic and improves code readability with its concise syntax.

Here, you'll explore techniques and tips for any(). You'll discover its real-world applications and get debugging advice to help you master this powerful function in your own Python projects.

Basic usage of any()

numbers = [0, False, 2, 0, ""]
result = any(numbers)
print(f"Are there any truthy values? {result}")
print(f"Empty list check: {any([])}")--OUTPUT--Are there any truthy values? True
Empty list check: False

The any() function scans the numbers list and returns True the moment it encounters a truthy value—in this case, the integer 2. This is known as short-circuiting, which makes the function efficient by not checking the entire iterable unnecessarily. Python treats certain values as falsy, including:

  • The integer 0
  • The boolean False
  • Empty strings like ""

Conversely, calling any() on an empty list returns False. This is a logical and important edge case to remember, as there are no elements to evaluate as true.

Common variations of using any()

While any() is great for simple checks, its real flexibility shines when you pair it with list comprehensions, other iterables, and custom predicates.

Using any() with list comprehensions

numbers = [1, 2, 3, 4, 5, 6]
has_even = any(num % 2 == 0 for num in numbers)
print(f"Does the list contain even numbers? {has_even}")--OUTPUT--Does the list contain even numbers? True

Combining any() with a generator expression like (num % 2 == 0 for num in numbers) is a memory-efficient way to run conditional checks. This approach avoids creating an entire new list in memory. Instead, it generates a sequence of boolean values one by one as any() iterates over them.

  • The condition num % 2 == 0 is applied to each number in the list.
  • any() evaluates the results, short-circuiting and returning True as soon as it finds the first even number, which is 2.

Using any() with different iterable types

print(f"Dictionary keys: {any({'a': 0, 'b': False})}")
print(f"Set values: {any({0, False, ''})}")
print(f"String characters: {any('0')}")
print(f"Generator: {any(x > 5 for x in range(10))}")--OUTPUT--Dictionary keys: True
Set values: False
String characters: True
Generator: True

The any() function is versatile and works with various iterable types beyond lists. When you pass it a dictionary, it checks the keys for truthiness, not the values. Since keys like 'a' are non-empty strings, the result is True.

  • Sets and Strings: For a set, any() returns False if all its elements are falsy, like 0 or False. When given a string, it treats each character as an element. Even a string like '0' evaluates to True because the character '0' itself is truthy.
  • Generators: The function also works seamlessly with generators. It evaluates items one by one and stops as soon as it finds a True value, which is an efficient way to handle potentially large sequences.

Using any() with custom predicates

def is_prime(n):
   if n < 2: return False
   return all(n % i != 0 for i in range(2, int(n**0.5) + 1))

numbers = [4, 6, 8, 9]
has_prime = any(is_prime(num) for num in numbers)
print(f"Contains any prime numbers? {has_prime}")--OUTPUT--Contains any prime numbers? False

You can pair any() with a custom function—a predicate—to perform more complex validations. In this example, the is_prime() function serves as the predicate. It's applied to each item in the numbers list using a generator expression, which is an efficient way to check conditions without creating a new list.

  • The expression is_prime(num) for num in numbers generates a boolean result for each number.
  • Since no number in [4, 6, 8, 9] is prime, the generator only yields False values.

Consequently, any() returns False because it doesn't find a single True value.

Advanced techniques with any()

Building on these fundamentals, you can write more sophisticated code by mastering any()’s short-circuit evaluation, combining it with other functions, and using it for data validation.

Short-circuit evaluation with any()

def check_value(x):
   print(f"Checking {x}")
   return x > 5

values = [1, 3, 7, 9, 2]
result = any(check_value(x) for x in values)
print(f"Final result: {result}")--OUTPUT--Checking 1
Checking 3
Checking 7
Final result: True

This example highlights the efficiency of any(). The function calls check_value() on each item in the list until it finds a condition that evaluates to True.

  • The function checks 1 and 3, which both fail the x > 5 test.
  • When it gets to 7, check_value() returns True.

At this point, any() stops immediately and returns True. It never evaluates the remaining numbers—9 and 2—making it highly efficient for large iterables or when function calls are computationally expensive.

Combining any() with other built-in functions

strings = ["hello", "world", "python"]
has_uppercase = any(map(lambda s: any(c.isupper() for c in s), strings))
print(f"Any strings contain uppercase? {has_uppercase}")

numbers = range(1, 10)
print(f"Any numbers over 100? {any(filter(lambda x: x > 100, numbers))}")--OUTPUT--Any strings contain uppercase? False
Any numbers over 100? False

You can make your checks more powerful by combining any() with other built-in functions like map() and filter(). For instance, you can nest any() inside a map() call to check if any string within a list contains an uppercase letter. The map() function applies the inner check to each string, and the outer any() evaluates the results.

  • Pairing any() with filter() lets you efficiently test a condition across a sequence. The example checks if any number in a range is greater than 100.
  • Since filter() yields no matching numbers, its iterator is empty, and any() correctly returns False.

Using any() for data validation

def validate_user(user):
   required_fields = ["name", "email", "password"]
   return not any(user.get(field) is None for field in required_fields)

user1 = {"name": "John", "email": "john@example.com", "password": "secret"}
user2 = {"name": "Jane", "email": None, "password": "123456"}
print(f"User1 valid: {validate_user(user1)}, User2 valid: {validate_user(user2)}")--OUTPUT--User1 valid: True, User2 valid: False

The any() function is a concise tool for data validation. In this example, validate_user() checks if a user dictionary contains all required fields with valid values. It uses a generator expression to iterate through required_fields and check if any are missing or set to None.

  • The expression any(user.get(field) is None ...) returns True if it finds just one missing or None value.
  • By using not, the logic is inverted. The function returns True only if all required fields are present and correctly filled out.

Move faster with Replit

Replit is an AI-powered development platform that transforms natural language into working applications. Describe what you want to build, and Replit Agent creates it—complete with databases, APIs, and deployment.

For the validation and checking techniques we've explored with any(), Replit Agent can turn them into production-ready tools.

  • Build a user registration validator that checks if any required fields are missing or invalid.
  • Create a content moderation tool that scans comments to see if they contain any words from a blocklist.
  • Deploy a password strength utility that confirms if a password meets criteria, like having any uppercase letters or numbers.

Describe your app idea, and Replit Agent writes the code, tests it, and fixes issues automatically, all in your browser. Try Replit Agent to bring your concepts to life.

Common errors and challenges

While any() is straightforward, a few common pitfalls can trip you up, from misunderstanding its inputs to using it inefficiently.

Forgetting that any() requires an iterable

A frequent mistake is passing a non-iterable argument, like a single integer or boolean, to any(). This will raise a TypeError because the function is designed to loop over a sequence, not evaluate a single value. Always ensure you're providing a list, tuple, set, or another iterable.

Misunderstanding how any() works with dictionaries

It's easy to assume any() checks the values in a dictionary, but it actually evaluates the keys. For example, any({'a': False, 'b': False}) returns True because the keys 'a' and 'b' are truthy non-empty strings. If you need to check the values, you must explicitly pass them using any(my_dict.values()).

Using list comprehensions instead of generators with any()

While using a list comprehension like any([x > 0 for x in numbers]) works, it's not the most efficient approach. This method builds an entire list of boolean values in memory before any() even starts its work. A generator expression—any(x > 0 for x in numbers)—is better because it produces values one at a time, allowing any() to short-circuit and save memory.

Forgetting that any() requires an iterable

The any() function needs a collection of items to check, such as a list or tuple. If you give it a single, non-iterable value like an integer, Python can't loop over it and will raise a TypeError. See this common error in action.

value = 42
result = any(value)  # This will raise TypeError
print(result)

Here, any() receives the integer 42 directly. Since the function can only loop over a collection of items, not a single number, Python raises a TypeError. The corrected implementation below shows the proper way to check a value.

value = 42
result = any([value])  # Wrap single value in a list
print(result)  # True

To fix the TypeError, you simply wrap the single value in a list, like any([value]). This gives the any() function an iterable to loop over. It checks the only element in the list, 42, finds it's a truthy value, and correctly returns True. Keep an eye out for this when working with variables that might hold a single item instead of a collection, as any() always expects an iterable.

Misunderstanding how any() works with dictionaries

It's a common mix-up: any() on a dictionary checks the keys, not the values. Since keys are typically truthy strings, you might get an unexpected True result even when all values are False. The following example demonstrates this behavior.

user_data = {"active": False, "verified": False}
is_valid = any(user_data)  # Only checks keys, not values
print(f"Is user valid? {is_valid}")  # Prints True

The function evaluates the keys "active" and "verified", not their values. Because these non-empty strings are truthy, the result is True. The corrected code below achieves the intended check.

user_data = {"active": False, "verified": False}
is_valid = any(user_data.values())  # Now checks the values
print(f"Is user valid? {is_valid}")  # Prints False

To correctly check the dictionary's values, you must call any(user_data.values()). This method passes an iterable of the values—in this case, False and False—to the function. Since no value is truthy, any() returns False as intended. It's a crucial distinction when you're validating data structures where the values, not the keys, hold the state you need to check.

Using list comprehensions instead of generators with any()

Using a list comprehension with any() works, but it's often inefficient. This method builds a complete list of boolean values in memory before the function can even start its check. The code below shows how this becomes a problem with large datasets.

numbers = range(1, 1000000)
has_large = any([num > 999990 for num in numbers])  # Creates entire list in memory
print(f"Contains large number: {has_large}")

This approach unnecessarily builds a list of nearly one million booleans in memory. This is inefficient because any() could find a True value and stop much earlier. The corrected code below avoids this problem entirely.

numbers = range(1, 1000000)
has_large = any(num > 999990 for num in numbers)  # Generator expression is more efficient
print(f"Contains large number: {has_large}")

By swapping the list comprehension for a generator expression—(num > 999990 for num in numbers)—the code becomes much more efficient. This approach avoids building a huge list in memory. Instead, it works by:

  • Generating values one at a time.
  • Allowing any() to short-circuit and stop as soon as it finds a True result.

This is the preferred method for large datasets, as it saves both memory and processing time.

Real-world applications

Now that you've seen the common pitfalls, you can confidently use any() for practical tasks like filtering files and detecting data anomalies.

Using any() for file filtering

You can use any() with functions like os.listdir() to quickly check if a directory contains files that match a specific pattern, such as a particular file extension.

import os

def has_python_files(directory):
   files = os.listdir(directory)
   return any(file.endswith('.py') for file in files)

current_dir = '.'
print(f"Does {current_dir} contain Python files? {has_python_files(current_dir)}")

The has_python_files() function shows a practical use for any() by interacting with the file system. It combines os.listdir() to get a list of filenames with a generator expression that checks each one.

  • The expression uses the endswith('.py') string method to test if a file is a Python script.
  • Because any() short-circuits, the function stops searching as soon as it confirms the first .py file, making the check very fast.

This is a great example of combining built-in tools for efficient file system operations.

Using any() for anomaly detection in data

In data analysis, the any() function offers an efficient way to spot outliers by checking if any value in a dataset falls outside a predefined statistical threshold.

def detect_anomalies(data, threshold):
   mean = sum(data) / len(data)
   std_dev = (sum((x - mean) ** 2 for x in data) / len(data)) ** 0.5
   return any(abs(x - mean) > threshold * std_dev for x in data)

temperatures = [20.5, 21.2, 20.8, 21.0, 35.7, 20.9]
print(f"Anomalies detected: {detect_anomalies(temperatures, 2)}")

The detect_anomalies function identifies outliers in a dataset. It first calculates the mean and standard deviation to establish a baseline for normal values. Then, it uses any() to check if any data point is an anomaly.

  • The generator expression checks if a value’s distance from the mean is greater than the threshold multiplied by the standard deviation.
  • In the temperatures list, the value 35.7 is far from the average.
  • any() finds this outlier, stops processing, and returns True, confirming an anomaly exists.

Get started with Replit

Turn your knowledge of any() into a real tool. Describe what you want to build to Replit Agent, like “a content moderation tool that flags any banned words” or “a password checker that verifies any required characters.”

The agent writes the code, tests for errors, and deploys your app automatically. Start building with Replit.

Get started free

Create and deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.

Get started for free

Create & deploy websites, automations, internal tools, data pipelines and more in any programming language without setup, downloads or extra tools. All in a single cloud workspace with AI built in.