The all()
function checks if all elements in an iterable (like a list, tuple, or set) are True. It returns True
if every element evaluates to True
; otherwise, it returns False
.
Syntax:
all(iterable)
The iterable can be a list, tuple, set, or any collection that can be looped through.
Example:
print(all([True, 1, "hello"])) # All values are True-like
Output:
True
Common Use Cases:
- Checking if All Values in a List Are Non-Zero:
numbers = [1, 2, 3, 4] print(all(numbers)) # Outputs True because all numbers are non-zero
- Validating Conditions in a Loop:
conditions = [x > 0 for x in [10, 20, 30]] print(all(conditions)) # Outputs True since all conditions are met
- Ensuring All Strings Are Non-Empty:
strings = ["apple", "banana", "cherry"] print(all(strings)) # Outputs True because all strings are non-empty
- Verifying User Inputs:
inputs = [True, True, True] print(all(inputs)) # Outputs True if all user inputs are valid (non-false)
Real-Life Use Cases:
- Data Validation: When checking if all entries in a form or dataset meet certain criteria.
data_valid = all(field != "" for field in user_input)
- Testing System Requirements: Verifying if all conditions are satisfied for running a script.
requirements = [cpu_ready, memory_ready, storage_ready] print(all(requirements)) # Ensures the system meets all conditions
- Ensuring Uniformity: Confirming that a collection has no
False
or invalid elements in a pipeline.