The any(iterable) built-in function returns True if at least one element of an iterable evaluates to True, or False if the collection is empty.
Short-Circuit Evaluation: any() evaluates elements lazily in O(1) auxiliary space and halts execution immediately upon encountering the first truthy item. To verify that every element satisfies a condition, see companion function all(). For conditional data extraction, pair any() with filter() or sequence traversal with zip().
The any() function accepts a single iterable and returns a boolean value:
# Formal syntax of built-in any()
result_bool = any(iterable)
| Parameter | Type Accepted | Behavioral Details |
|---|---|---|
iterable |
Iterable[T] |
Any Python iterable container (list, tuple, string, set, dict, or generator). |
| Return Value | bool |
Returns True if bool(x) is true for any element; returns False if empty or all items are falsy. |
The relationship between any() and all() corresponds to mathematical existential (∃) versus universal (∀) quantification:
| Elements in Iterable | any() Output |
all() Output |
Logical Meaning |
|---|---|---|---|
All elements are True |
True |
True |
Full satisfaction |
At least one True, others False |
True |
False |
Partial satisfaction |
All elements are False |
False |
False |
Zero satisfaction |
Empty Iterable [] |
False |
True |
Vacuous truth in formal logic |
In Python, elements evaluate according to their truth value testing rules:
# 1. Lists with boolean and numerical truthiness
print("Empty list: ", any([])) # False
print("All False or zeros: ", any([0, False])) # False
print("At least one truthy: ", any([0, False, 1]))# True
# 2. String truthiness (non-empty strings are truthy)
print("Standard text: ", any("plus2net")) # True
print("Literal string 'False':", any("False")) # True (characters are non-empty!)
print("Empty string: ", any("")) # False
Output:
Empty list: False
All False or zeros: False
At least one truthy: True
Standard text: True
Literal string 'False': True
Empty string: False
When checking a dictionary directly, Python iterates over its keys, completely ignoring the associated values:
# 1. Tuples evaluation
print("Tuple (True, 0): ", any((True, 0))) # True
print("Tuple (0, 0): ", any((0, 0))) # False
print("Tuple (0, 1): ", any((0, 1))) # True
# 2. Dictionaries evaluate KEYS only, never values
print("Key 0 (falsy) & 1 (truthy):", any({0: 'A', 1: 'B'})) # True
print("Key 0 only (falsy): ", any({0: 'A'})) # False
print("Key 0 only with True value:", any({0: True})) # False! (key is 0)
print("Explicit values evaluation:", any({0: True}.values())) # True (checks values)
Output:
Tuple (True, 0): True
Tuple (0, 0): False
Tuple (0, 1): True
Key 0 (falsy) & 1 (truthy): True
Key 0 only (falsy): False
Key 0 only with True value: False
Explicit values evaluation: True
any() executes with short-circuit logic: the moment it encounters an element whose bool(x) is True, it returns immediately without evaluating the remainder of the iterable:
# Generator with print to observe short-circuit evaluation
def evaluate_stream():
for x in [0, False, 42, 100]:
print(f" Checking element: {x}")
yield x
print("Starting any() check:")
res = any(evaluate_stream())
print("Result of any():", res)
Output:
Starting any() check:
Checking element: 0
Checking element: False
Checking element: 42
Result of any(): True
any(x > 0 for x in stream)) rather than a list comprehension (e.g. any([x > 0 for x in stream])). Generator expressions allow any() to halt on the first true item without creating the rest of the list.
Below are real-world recipes utilizing any() for permission checks and filename validation:
# Recipe A: Checking multiple user permission flags
user_permissions = {"read": True, "write": False, "admin": False}
required_roles = ["admin", "superadmin"]
# Check if user possesses at least one elevated role
has_access = any(user_permissions.get(role, False) for role in required_roles)
print("Elevated access granted:", has_access)
# Recipe B: Substring search across file extensions
filename = "report_2026_q3.pdf"
supported_extensions = [".pdf", ".docx", ".xlsx"]
is_valid_format = any(filename.endswith(ext) for ext in supported_extensions)
print("File format supported:", is_valid_format)
Output:
Elevated access granted: False
File format supported: True
any(my_dict.values())."False" or "0" are non-empty and evaluate to True.any([check(x) for x in data]) forces evaluation of every item, destroying short-circuit advantages. Use parentheses any(check(x) for x in data) instead.# Pitfall 1: Dictionary keys vs dictionary values
user_status = {"guest": False, "verified": False}
# Trap: any(user_status) checks non-empty keys ('guest', 'verified') which are True!
print("Checks keys (Trap): ", any(user_status)) # True!
print("Checks values (Correct):", any(user_status.values())) # False
# Pitfall 2: String "0" and "False" are truthy in Python!
print("bool('False'):", bool('False')) # True
print("any(['False']):", any(['False']))# True
Output:
Checks keys (Trap): True
Checks values (Correct): False
bool('False'): True
any(['False']): True
Practice short-circuit benchmarks, dictionary key validations, and generator expressions in our companion Jupyter Notebook:
Explore interactive code cells, benchmark short-circuit speedups, test multi-permission gates, and run self-validating assertions.
View on GitHub Run in Google ColabRun these unit checks directly in Python or your local environment to verify any() mechanics:
def test_any_mechanics():
# 1. Empty container returns False
assert any([]) is False
assert any(set()) is False
# 2. Truthy item yields True
assert any([0, 0, 1]) is True
assert any((False, True)) is True
# 3. String characters
assert any("a") is True
assert any("") is False
# 4. Dictionary keys check
assert any({0: True}) is False
assert any({1: False}) is True
assert any({0: True}.values()) is True
print("All any() unit assertions passed! 100% verified.")
test_any_mechanics()
Output:
All any() unit assertions passed! 100% verified.
Returns True if every element of an iterable evaluates to True.
Extracts elements from an iterable matching a boolean predicate condition.
Combines elements from multiple iterables in parallel into unified tuples.
Pairs an iterable's items with an automatically incremented integer counter.
Author & Instructor at plus2net
I write and maintain practical tutorials on Python, PHP, SQL, JavaScript, HTML, jQuery, and web development at plus2net. The tutorials focus on clear explanations, working examples, and code that readers can test and adapt while learning.