Definition of the any() function in Python
The any() function is a built-in function in Python that checks whether at least one element of an iterable evaluates to True. It returns True as soon as it finds a truthy element, and False if all elements are false or if the iterable is empty.
If you want to master Python's built-in functions like any() and many others, our comprehensive Python course will guide you step by step through your learning journey.
The any() function is one of the fundamental tools in Python for performing logical checks on data collections. It works with any type of iterable: list, tuple, set, dict, generators, and many more.
Remember this simple rule: any() returns True if there is at least one truthy element in the iterable. If the iterable is empty, it returns False.
Syntax and behavior
The syntax of any() is extremely simple. It accepts a single argument: an iterable.
any(iterable)Here is how it works in detail:
- It iterates through the iterable element by element.
- As soon as an element evaluates to
True(i.e., it is truthy), it immediately returnsTruewithout iterating through the rest. - If no element is truthy (all are falsy), it returns
False. - If the iterable is empty, it returns
False.
This short-circuit evaluation behavior is very important for performance: Python stops the evaluation as soon as the result is determined.
Understanding truthy and falsy values
To use any() effectively, you need to understand which values Python considers as false (falsy). Here is a summary table:
| Value | Boolean evaluation | Type |
|---|---|---|
False | Falsy | bool |
None | Falsy | NoneType |
0 | Falsy | int |
0.0 | Falsy | float |
"" (empty string) | Falsy | str |
[] (empty list) | Falsy | list |
() (empty tuple) | Falsy | tuple |
{} (empty dict) | Falsy | dict |
set() (empty set) | Falsy | set |
| Everything else | Truthy | Various |
Any value that is not in this list of falsy values is considered truthy by Python. This includes non-zero numbers, non-empty strings, non-empty collections, objects, etc.
Practical examples
Basic usage with lists
Let's start with the simplest cases to understand the behavior of any():
# At least one element is True
result = any([False, False, True, False])
print(result) # True
# All elements are False
result = any([False, False, False])
print(result) # False
# Empty list
result = any([])
print(result) # False
# With numeric values
result = any([0, 0, 0, 1])
print(result) # True (1 is truthy)
# With strings
result = any(["", "", "hello"])
print(result) # True ("hello" is truthy)Usage with conditions and comprehensions
One of the most powerful uses of any() is its combination with generator expressions. You can test a condition on each element of an iterable in a concise and performant way:
# Check if at least one number is even
numbers = [1, 3, 5, 7, 8, 9]
result = any(n % 2 == 0 for n in numbers)
print(result) # True (8 is even)
# Check if a list contains at least one negative number
values = [10, 25, -3, 42, 7]
has_negative = any(v < 0 for v in values)
print(has_negative) # True (-3 is negative)
# Check if a word starts with an uppercase letter
words = ["python", "java", "Ruby", "go"]
has_uppercase = any(word[0].isupper() for word in words)
print(has_uppercase) # True ("Ruby")Prefer generator expressions (without brackets) over list comprehensions (with brackets) when using any(). The generator expression benefits from short-circuit evaluation and does not create the entire list in memory.
Usage with dictionaries
When you use any() with a dict, it iterates over the keys by default:
# By default, any() iterates over keys
my_dict = {0: "zero", "": "empty", "key": "value"}
result = any(my_dict)
print(result) # True ("key" is truthy)
# Test the dictionary values
grades = {"Alice": 0, "Bob": 0, "Charlie": 15}
someone_has_grade = any(my_dict.values())
print(someone_has_grade) # True
# Check if at least one student passed
students = {"Alice": 8, "Bob": 12, "Charlie": 6}
someone_passed = any(grade >= 10 for grade in students.values())
print(someone_passed) # True (Bob has 12)Usage with strings
Since strings are iterables in Python, any() can iterate through them character by character:
# Check if a string contains at least one digit
text = "Hello world 2024"
contains_digit = any(c.isdigit() for c in text)
print(contains_digit) # True
# Check if a string contains at least one uppercase letter
password = "mypassword"
has_uppercase = any(c.isupper() for c in password)
print(has_uppercase) # False
# Password validation
def validate_password(pwd):
has_upper = any(c.isupper() for c in pwd)
has_lower = any(c.islower() for c in pwd)
has_digit = any(c.isdigit() for c in pwd)
has_special = any(not c.isalnum() for c in pwd)
long_enough = len(pwd) >= 8
return all([has_upper, has_lower, has_digit, has_special, long_enough])
print(validate_password("MyP@ss1!")) # True
print(validate_password("weak")) # FalseComparison between any() and all()
The any() function has a sister function: all(). It is essential to understand the difference between the two:
| Function | Returns True if... | Empty iterable | Logic |
|---|---|---|---|
any() | At least one element is truthy | False | Logical OR |
all() | All elements are truthy | True | Logical AND |
numbers = [1, 2, 0, 4, 5]
print(any(numbers)) # True (at least one is truthy)
print(all(numbers)) # False (0 is falsy)
# All positive vs at least one positive
values = [-1, -2, 3, -4]
print(any(v > 0 for v in values)) # True (3 > 0)
print(all(v > 0 for v in values)) # False (some are negative)
# With an empty iterable
print(any([])) # False
print(all([])) # True (logical convention)Equivalent implementation of any()
To fully understand the internal workings of any(), here is an equivalent implementation in pure Python:
def my_any(iterable):
for element in iterable:
if element:
return True
return False
# Test
print(my_any([0, False, None, "", 42])) # True
print(my_any([0, False, None, ""])) # False
print(my_any([])) # FalseAs you can see, the behavior is very simple: the loop stops as soon as a truthy element is found thanks to the return True.
Advanced use cases
File and data validation
The any() function is very useful in the context of data validation:
# Check if at least one file has a dangerous extension
files = ["report.pdf", "image.png", "script.exe", "notes.txt"]
dangerous_extensions = [".exe", ".bat", ".cmd"]
has_dangerous_file = any(
file.endswith(ext)
for file in files
for ext in dangerous_extensions
)
print(has_dangerous_file) # True (script.exe)
# Check if a user has the required permissions
user_permissions = ["read", "comment"]
admin_permissions = ["write", "delete", "admin"]
is_admin = any(p in admin_permissions for p in user_permissions)
print(is_admin) # FalseUsage with custom objects
You can use any() with your own class by defining the __bool__ method:
class Product:
def __init__(self, name, stock):
self.name = name
self.stock = stock
def __bool__(self):
return self.stock > 0
def __repr__(self):
return f"Product('{self.name}', stock={self.stock})"
products = [
Product("Keyboard", 0),
Product("Mouse", 0),
Product("Monitor", 5),
]
# Check if at least one product is in stock
print(any(products)) # True (Monitor has stock)
# With an explicit condition
print(any(p.stock > 10 for p in products)) # FalseCombination with map() and filter()
The any() function combines elegantly with other Python built-in functions:
# With map()
numbers = ["10", "abc", "20", "xyz"]
def is_numeric(s):
try:
int(s)
return True
except ValueError:
return False
result = any(map(is_numeric, numbers))
print(result) # True
# With a lambda function
my_list = [1, 3, 5, 7, 9]
has_even = any(map(lambda x: x % 2 == 0, my_list))
print(has_even) # False (all odd)Best practices
Here are the best practices to follow when using any() in Python:
- Use generator expressions rather than list comprehensions with
any(). Writeany(x > 5 for x in my_list)and notany([x > 5 for x in my_list]). The generator expression benefits from short-circuit evaluation and consumes less memory. - Prefer
any()over manual loops to test whether an element satisfying a condition exists. It's more readable, more concise, and more idiomatic. - Don't confuse
any()andall(). Remember:any()= logical OR,all()= logical AND. - Be careful with empty iterables:
any([])returnsFalse. This is logical (no element can be true), but it can be surprising if you don't anticipate it. - Use
any()for validation: it's perfect for checking that at least one condition is met in a set of criteria.
Warning: do not use any() when you need to know which element is truthy. In that case, use a for loop with a condition, or the next() function with a generator expression instead.
# ❌ any() doesn't tell you WHICH element is true
result = any(n > 100 for n in numbers)
# ✅ If you need the element, use next()
element = next((n for n in numbers if n > 100), None)
# ✅ Or a for loop
for n in numbers:
if n > 100:
print(f"Found: {n}")
breakPerformance and optimization
The any() function is optimized in C in the CPython implementation, which makes it very fast. Here are some key points to know:
import time
# Performance comparison: loop vs any()
numbers = list(range(1_000_000))
# With any() - short-circuits at the first truthy element
start = time.time()
result = any(n > 0 for n in numbers)
end = time.time()
print(f"any(): {end - start:.6f}s") # Very fast (short-circuit)
# With a manual loop
start = time.time()
found = False
for n in numbers:
if n > 0:
found = True
break
end = time.time()
print(f"Loop: {end - start:.6f}s") # Similar but less readableIn this example, any() stops at the second element (1 > 0), regardless of the list's size. This is the major advantage of short-circuit evaluation.
Frequently asked questions
What is the difference between any() and all() in Python?
The any() function returns True if at least one element of the iterable is truthy (logical OR). The all() function returns True if all elements are truthy (logical AND). Additionally, any([]) returns False while all([]) returns True. Both functions use the short-circuit mechanism to optimize performance.
Does the any() function modify the original iterable?
No, any() never modifies the iterable it receives. It is a non-destructive function that simply iterates through elements to evaluate their truth value. However, if you pass it a generator, it will be partially or fully consumed after the call (the generator will advance up to the truthy element or to the end).
Can you use any() with lambda functions?
Yes, you can combine any() with lambda via the map() function. For example: any(map(lambda x: x > 10, my_list)). However, in most cases, a generator expression is more readable: any(x > 10 for x in my_list). Both approaches are equivalent in terms of functionality and performance.
How can I learn to use any() and Python's built-in functions effectively?
To master any() as well as all of Python's built-in functions, regular practice is essential. You can follow our dedicated Python course on Believemy which covers in depth built-in functions, iterables, generators, and Python programming best practices. Combine this with personal projects to consolidate your knowledge.