The any() function was introduced in Python 2.5 for convenient checking: whether there is at least one true element in an iterable object (for example, a list, tuple, generator). It is useful when you need to check whether at least one condition from many is met.
Historically, without it, you had to write a loop with a break upon finding an element or combine map and reduce — it was cumbersome and slow. The main problem that any() solves is the conciseness and readability of such checks.
The solution — any() and all() work with lazy evaluation (they stop as soon as they find False or True respectively). It is important to understand the difference: any() returns True upon the first true element, while all() returns True if all elements are true.
Example code:
nums = [0, 0, 3, 0] if any(nums): print('There is a non-zero element in the list')
Key features:
What happens if you pass an empty list as an argument to any()?
any() will return False. This makes sense: there are no true elements in an empty sequence.
How is any() fundamentally different from all()?
any() checks for the presence of at least one true value. all() checks the truth of all values. Their results are opposite only for strictly empty collections.
Can you use any() with a generator that might be infinite?
Yes, you can, and thanks to lazy evaluation, any will stop as soon as it encounters True. If the generator never yields True, the function will not finish on its own.
def infinite_gen(): while True: yield 0 # any(infinite_gen()) — will run infinitely if there are no exit conditions
Want to check that at least one value is not None:
values = [None, None, None] if any(values): do_something() # Will never execute if we just forgot that None == False
Pros:
Cons:
Correct application — to look for at least one user over 30:
users = [{'age': 25}, {'age': 35}] if any(u['age'] > 30 for u in users): print('There is a user over 30')
Pros:
Cons: