🕯️ Magic Note
any() takes an iterable of boolean values (or values that can be evaluated as booleans) and returns True if any element is truthy. The magic is in the short circuit behavior. As soon as any() encounters the first truthy value, it returns True immediately without looking at the remaining items.
- Short circuits, stops at the first truthy value
- Returns False for empty iterables
- Can be used with any iterable: lists, tuples, sets, generators
- Perfect companion to all() which checks if every item is truthy
| Input Values | any() Result |
|---|---|
| [False, False, False] | False |
| [False, True, False] | True |
| [“”, 0, None, “magic”] | True |
| [] | False |
| [1, 2, 3] | True |
Python
# Checking if any number is even
numbers = [1, 3, 5, 7, 8, 11]
has_even = any(n % 2 == 0 for n in numbers)
print(has_even)
# Output: True
# Stops at 8, does not check 11
Python
# Checking for empty strings in a list
texts = [“hello”, “world”, “”, “python”]
has_empty = any(t == “” for t in texts)
print(has_empty)
# Output: True
Python
# Combining any with all for validation
user_inputs = [“name”, “”]
if any(i == “” for i in user_inputs):
print(“Missing required fields”)
elif all(i.isalpha() for i in user_inputs if i):
print(“All inputs are valid letters”)
# Output: Missing required fields
- Forgetting that any() short circuits, then wondering why a generator with side effects didn’t run completely
- Using any() on an empty list expecting True, it returns False
- Confusing any() with all(), using one when you need the other
⚡ Whisper
You do not need to taste every bean to know if one is burnt. One spark is enough. The moment truth appears, the search ends. Efficiency is its own magic.