Python all() Function



The Python all() function is a built-in function that returns True if all the elements of a given iterable, such as a list, tuple, set, or dictionary are truthy, and if any of the values is falsy, it returns False. However, it returns True if the iterable object is empty.

An iterable is an object that allows us to retrieve its item through iteration. In Python, any non-empty string and iterables and any non-zero values are considered as True. Whereas the empty iterables and strings, the number 0 and the value None are considered as False.

Syntax

Following is the syntax of the Python all() function −

all(iterable)

Parameters

The Python all() function accepts a single parameter −

  • iterable − This parameter indicates an iterable object such as a list, tuple, dictionary, or set.

Return Value

The Python all() function returns a Boolean value.

Examples

The below example demonstrates the working of all() function −

Example 1

The following example shows the usage of Python all() function. Here we are creating a list named 'numerics' and applying all() function to check whether the given list contains truthy values.

numerics = [71, 87, 44, 34, 15]
output = all(numerics)
print("The output after evaluation:", output)

When we run the above program, it produces the following result −

The output after evaluation: True

Example 2

In the code below we will create a list of fruits and then check if it contains truthy value or not using all() function.

fruit_names = ["carrot", "banana", "dragon fruit", "orange"]
output = all(fruit_names)
print("The output after evaluation:", output)

Following is the output of above code −

The output after evaluation: True

Example 3

In the following example, we use the all() function on a list with a false value. Since the list contains an empty String, the method will return False.

numerics = [71, 87, 44, 34, 15, "", 5]
output = all(numerics)
print("The output after evaluation:", output)

Output of the above code is as follows −

The output after evaluation: False

Example 4

In this example, we use the all() function on an empty list. In this case, the method will return True as an empty iterable is considered to have all truthy values by default.

empty_numerics = []
output = all(empty_numerics)
print("The output after evaluation:", output)

Following is an output of the above code −

The output after evaluation: True
python_built_in_functions.htm
Advertisements