What is the all() method in Python?
Overview
In Python, the all() method checks if the elements in the given iterable (list, tuple) are true. It returns True if all the elements in the iterable are true. Otherwise, it returns False.
Syntax
The syntax of the all() method is given below:
all(iterable)
Parameter
iterable: This represents any iterable such as a list or tuple that contains the elements.
Return type
The all() method returns a boolean value such as true or false.
Return value
The all() returns True if all the elements in the iterable are true. Otherwise, it returns False.
Code
The following code shows how to use the all() method in Python:
# create a listmy_list = [True, True, True,]# Assign result to variable resultresult = all(my_list)print(f"Output: {result}")# create a listmy_list = [0, 1, 14, 7]# Assign result to variable resultresult = all(my_list)print(f"Output: {result}")# create a listmy_list = [20, 40, 7, 6]# Assign result to variable resultresult = all(my_list)print(f"Output: {result}")
Explanation
-
Line 2: We declare a list named
my_listwith three elements. -
Line 4: We pass
my_listto theall()method to check if all elements in the list are true. Then, we store the result in a new variable namedresult. -
Line 5: The result is displayed using the
print()statement. -
Line 7: We reassign elements to
my_list. -
Line 9: We pass
my_listto theall()method to check if all elements in the list are true. Then, we store the result in the variable namedresult. -
Line 10: The result is displayed using the
print()statement. -
Line 12: We reassign elements to
my_list. -
Line 14: We pass
my_listto the methodall()to check if all elements in the list are true. Then, we store the result in the variable namedresult. -
Line 15: The result is displayed using the
print()statement.
Note: If the list is empty, the method
all()returnsTrue.