The all()
function in Python is a built-in function that takes an iterable (such as a list, tuple, or set) as an argument and returns True
if all the elements in the iterable are evaluated as True
. If the iterable contains any elements that are evaluated as False
, 0
, None
, or an empty string, the all()
function will return False
.
Here's the syntax of the all()
function:
all(iterable)
The iterable
argument can be any iterable object, such as a list, tuple, set, or even a string. The all()
function will iterate over the elements of the iterable and check if all the elements are evaluated as True
. If all elements are True
, it will return True
; otherwise, it will return False
.
Here are a few examples to illustrate the usage of the all()
function:
numbers = [2, 4, 6, 8, 10]
result = all(num % 2 == 0 for num in numbers)
print(result) # Output: True
In this example, the all()
function checks if all the numbers in the list are even. Since all the numbers satisfy the condition num % 2 == 0
, the all()
function returns True
.
fruits = ['apple', 'banana', 'cherry', '']
result = all(fruit for fruit in fruits)
print(result) # Output: False
In this example, the all()
function checks if all the elements in the list of fruits are non-empty strings. Since the empty string ''
evaluates as False
, the all()
function returns False
.
numbers = [3, 5, 7, 9, 11]
result = all(num % 2 == 0 for num in numbers)
print(result) # Output: False
In this example, the all()
function checks if all the numbers in the list are even. Since none of the numbers satisfy the condition num % 2 == 0
, the all()
function returns False
.
Note that if the iterable passed to the all()
function is empty, it will return True
because there are no elements that evaluate to False
.