Python all() Function
The all() function in Python checks whether all elements in an iterable are true. If they are, it returns True. Otherwise, it returns False.
Syntax
all(iterable)
Parameters:
iterable– A list, tuple, set, dictionary, or any iterable object.
Returns:
True– If all elements in the iterable are true (or the iterable is empty)False– If any element is false
Example 1: Using all() with a List of Booleans
values = [True, True, True]
print(all(values))
True
Example 2: With One False Value
values = [True, False, True]
print(all(values))
False
Example 3: Checking Numbers (Zero is False)
numbers = [1, 2, 3, 0]
print(all(numbers))
False
0 is considered False in Python.
Example 4: Empty Iterable
print(all([]))
True
This might seem strange, but in logic, a universal statement about an empty set is considered true.
Use Case: All Elements Greater Than 0
nums = [5, 8, 12, 3]
result = all(n > 0 for n in nums)
print(result)
True
Use Case: Validating All Inputs
inputs = ["name", "email", ""]
print(all(inputs))
False
This is useful in form validation — one empty string makes all() return False.
Common Mistakes
- Passing non-iterables like integers will raise a
TypeError - Assuming
all()checks a condition itself — it only evaluates the truthiness of elements
Interview Tip
all() is often used with list comprehensions or generator expressions to verify conditions across a dataset.
Summary
all()returnsTrueonly if every element is true0,False,"",[], etc., are considered false- Very useful for condition checks and validation
Practice Problem
Write a program that takes a list of ages and prints "All adults" if all are 18 or older.
ages = [22, 34, 19, 45]
if all(age >= 18 for age in ages):
print("All adults")
else:
print("Not all are adults")
Comments
Loading comments...