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 list
my_list = [True, True, True,]
# Assign result to variable result
result = all(my_list)
print(f"Output: {result}")
# create a list
my_list = [0, 1, 14, 7]
# Assign result to variable result
result = all(my_list)
print(f"Output: {result}")
# create a list
my_list = [20, 40, 7, 6]
# Assign result to variable result
result = all(my_list)
print(f"Output: {result}")

Explanation

  • Line 2: We declare a list named my_list with three elements.

  • Line 4: We pass my_list to the all() method to check if all elements in the list are true. Then, we store the result in a new variable named result.

  • Line 5: The result is displayed using the print() statement.

  • Line 7: We reassign elements to my_list.

  • Line 9: We pass my_list to the all() method to check if all elements in the list are true. Then, we store the result in the variable named result.

  • Line 10: The result is displayed using the print() statement.

  • Line 12: We reassign elements to my_list.

  • Line 14: We pass my_list to the method all() to check if all elements in the list are true. Then, we store the result in the variable named result.

  • Line 15: The result is displayed using the print() statement.

Note: If the list is empty, the method all() returns True.

Free Resources