any() — at least one True
any() returns True if at least one item is truthy:
# Check if any number is even:
numbers = [1, 3, 5, 8, 9]
print(any(x % 2 == 0 for x in numbers)) # True (8 is even)
# Check if any string is empty:
strings = ["hello", "world", ""]
print(any(not s for s in strings)) # True (empty string is falsy)
# All False:
print(any([False, False, False])) # False
all() — all must be True
all() returns True only if all items are truthy:
# Check if all numbers are positive:
numbers = [1, 2, 3, 4, 5]
print(all(x > 0 for x in numbers)) # True
# Check if all strings are non-empty:
strings = ["hello", "world", "python"]
print(all(s for s in strings)) # True
# One False:
print(all([True, True, False])) # False
With generator expressions
# Check if all ages are 18+:
ages = [20, 25, 30, 18]
all_adults = all(age >= 18 for age in ages)
print(all_adults) # True
# Check if any name starts with 'A':
names = ['Alice', 'Bob', 'Charlie']
has_a_name = any(name.startswith('A') for name in names)
print(has_a_name) # True
Empty sequences
# Empty sequences:
print(any([])) # False (no True values)
print(all([])) # True (no False values - vacuously true)
When to use
any(): Check if at least one item meets conditionall(): Check if all items meet condition- More readable than loops for these checks
- Works with any iterable (lists, generators, etc.)