Note
Python - any() - Check for truthy values in an iterable
Overview of the Python any() function. Check if any object in iterable is truthy.
any(iterable) returns True if any object in provided iterable is "truthy".
That means that if at least one item evaluates to True, any() returns True.
If all items are "falsy" (evaluating to False) (or if the iterable is empty), any() returns False.
In Python, values like 0, None, [], {}, "", and () are "falsy" and evaluate to False.
Any non-zero numbers, non-empty containers, and most other objects are considered "truthy."
A truthy objects returns True after calling bool(object).
my_list = [0, 1, None, ()]
result = any(my_list)
print(result) # True
Output:
True
It returns True because from my_list value 1 is truthy.
my_list = [0, [], None, ()]
result = any(my_list)
print(result) # False
Output:
False
Not a single object in my_list is truthy now.
Using any() with an empty iterable
my_list = []
result = any(my_list)
print(result) # False
Output:
False
Key Points to Remember about any()
-
Evaluates Truthiness:
any()checks if at least one element in an iterable is truthy. -
Default for Empty Iterables: When the iterable is empty,
any()returnsFalse. -
Common Use Cases:
any()is often used to quickly verify if a list or other iterable contains at least one truthy value.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!