Note
Python - all() - Check truthiness of all elements in an iterable
Overview of the Python all() function. Check if all objects in iterable are truthy.
all(iterable) returns True if all objects in provided iterable are "truthy".
If every item evaluates to True, all() returns True. If even one item is "falsy" (evaluating to False), all() returns False.
Important - If the iterable is empty, all() returns True by default!
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 = [5, 1, "devcuriosity", True]
result = all(my_list)
print(result) # True
Output:
True
my_list = [5, 1, "devcuriosity", False]
result = all(my_list)
print(result) # False
Output:
False
Using all() with an empty iterable
my_tuple = []
result = all(my_tuple)
print(result) # True
Output:
True
It's important to remember about this feature of all() because it might be a bit counterintuitive.
Key Points to remember about all()
-
Evaluates Truthiness:
all()checks if all elements in an iterable are truthy. -
Default for Empty Iterables: When the iterable is empty,
all()returnsTrueby default. -
Common Use Cases:
all()is commonly used to verify that all items are truthy.
I hope you found this helpful! If you have any feedback, questions or requests, please reach out to me through Contact page!