Python all() function checks if every element in an iterable (like a list or tuple) is True. It returns True only if all elements are True or if the iterable is empty. It’s a quick way to verify conditions across a collection.
all()
Syntax
result = all(iterable)
result
: Stores the True/False outcome of theall()
check.all()
: The built-in Python function performing the check.iterable
: The list, tuple, or other collection you want to evaluate.
Example 1: Checking if All Elements in a List Are True with Python all()
my_list = [True, 1, "hello"]
result = all(my_list)
print(result)
Code Explanation
- Line 1: Creates a list with various True-equivalent values.
- Line 2: Applies
all()
tomy_list
. Since all elements are truthy,result
becomes True. - Line 3: Prints the outcome (True) to the console.
Output
True
Example 2: How Python all()
Works for Lists?
my_list = [1, 2, 3, 4]
result = all(my_list)
print(result)
my_list_with_zero = [1, 2, 0, 4]
result = all(my_list_with_zero)
print(result)
empty_list = []
result = all(empty_list)
print(result)
Code Explanation
- For lists,
all()
checks each element - An empty list is considered True
- If any element in the list evaluates to False, then
all()
returns False
Output
True
False
True
Example 3: Checking if All Elements in a List Meet a Condition with Python all()
numbers = [2, 4, 6, 0]
result = all(num % 2 == 0 for num in numbers)
print(result)
Code Explanation
- Line 1: Creates a list of numbers.
- Line 2: Uses a generator expression within
all()
. It checks if eachnum
is even. Since 0 is present (and 0 % 2 == 0 is True),result
is False. - Line 3: Prints the outcome (False) to the console.
Output
False
Example 4: How Python all()
Works for Strings?
my_string = "Hello World"
result = all(my_string)
print(result)
empty_string = ""
result = all(empty_string)
print(result)
Code Explanation
- In the case of strings,
all()
considers any non-empty string as True. Even a string with just whitespace is considered True. - An empty string is evaluated as False.
Output
True
True
Example 5: How Python all()
Works with Python Dictionaries?
my_dict = {'a': 1, 'b': 2, 'c': 3}
result = all(my_dict)
print(result)
empty_dict = {}
result = all(empty_dict)
print(result)
my_dict_with_false = {'a': 1, 'b': 0, 'c': 3}
result = all(my_dict_with_false)
print(result)
Code Explanation
- For dictionaries,
all()
checks the keys, not the values - An empty dictionary is considered True
- If any key in the dictionary evaluates to False, then
all()
returns False
Output
True
True
False