Junior — Middle
What is the purpose of the all() method in Python and in what situations is it used?
sobes.tech AI
Answer from AI
The all() method in Python is used to check if all elements of an iterable are true (True) in a boolean context. If all elements are true or the iterable is empty, all() returns True; otherwise, it returns False.
It is used when you need to ensure that all conditions or elements satisfy a certain criterion. For example, to check that all numbers in a list are positive:
numbers = [1, 2, 3, 4]
if all(n > 0 for n in numbers):
print("All numbers are positive")
else:
print("There are non-positive numbers")
This is useful for data validation, condition checking in loops, and filtering.