Python all

Summary: in this tutorial, you will learn how to use the Python all() function to check if all elements of an iterable are true.

Introduction to the Python all() function

The Python all() function accepts an iterable and returns True if all elements of the iterable are True. It also returns True if the iterable is empty.

Here’s the syntax of the all() function:

all(iterable)Code language: Python (python)

The following example illustrates all() functions:

mask = [True, True, False]
result = all(mask)
print(result)  # 👉 False

mask = [True, True, True]
result = all(mask)
print(result)  # 👉 True

result = all([])
print(result)  # 👉 TrueCode language: Python (python)

How it works.

  • First, [True, True, False] has an element with the value False, the all() function returns False.
  • Second, [True, True, True] has all elements with value True, the all() function returns True.
  • Third, [] is an empty iterable, therefore, the all() function also returns True.

Practical examples of the all() function

Let’s take some practical examples of using the all() function.

1) Using Python all() function to make a complex condition more simple

The following example checks if the length of v is greater than zero and less than 25 and if it contains only alphanumeric characters:

v = 'Python'
if len(v) > 0 and len(v) < 25 and v.isalnum():
    print(v)Code language: Python (python)

The condition is quite complex. To make it shorter, you can replace all the and operators with the all() function like this:

v = 'Python'
valid = all([len(v) > 0, len(v) < 25, v.isalnum()])
if valid:
    print(v)Code language: Python (python)

In this example, The valid evaluates to True if all the conditions inside the tuple passed to the all() the function returns True.

2) Using Python all() function to validate iterables of numbers

The following example uses the all() function to check if all numbers of an iterable are greater than or equal to four:

ratings = [3, 5, 4, 2, 4, 5]
has_good_rating = all([rating >= 4 for rating in ratings])
print(has_good_rating)  # falseCode language: Python (python)

How it works.

First, use a list comprehension to convert the list of ratings to a list of True and False. The following

[rating >= 4 for rating in ratings]Code language: Python (python)

returns a list of boolean values:

[False, True, True, False, True, True]Code language: Python (python)

Second, pass the result of the list comprehension to all() function. So all() function returns False because the list contains some False elements.

Summary

  • Use the Python all() function to check if all elements of an iterable are true.
Did you find this tutorial helpful ?