Python all()

Table of Contents

Introduction

The all() function in Python is used to check if all elements are True in an iterable.

If you are looking for the way to solve such a problem then you are in the right place, keep reading this article to know how to use this feature best.

This article will explain all the peculiarities of the all() function with many examples.

Python all() function

The all() function in Python returns True if elements of an iterable are True, otherwise False.
If the iterable is empty the all() function returns True.

The syntax is very simple and the same for all iterables:

all(my_iterable)

By following this link you can find the official Python documentation.

In the following sections you will find examples for the most frequent iterables, i.e. lists, tuples, strings, dictionaries and sets.

Python all() function – Examples

Lists

A list can contain objects of various types.
Depending on the type of the elements in the list, the all() function will return True or False.

Check out these examples below:

print(all([False, False, False]))
print(all([True, True, True]))
print(all([1, 2, 3]))
print(all([1, 0, 2]))
print(all([]))

Output

False
True
True
False
True

Tuples

As in the case of lists, tuples can also contain objects of various types.
Depending on the type of the elements of the tuple, the all() function will return True or False.

Check out these examples below:

print(all((False, False, False)))
print(all((True, True, True)))
print(all((1, 2, 3)))
print(all((1, 0, 2)))
print(all(()))

Output

False
True
True
False
True

Strings

Strings are always verified (True) even the empty string.

print(all("A Python string"))
print(all("False"))
print(all("0"))
print(all(""))

Output

True
True
True
True

Dictionaries

In the case of dictionaries, Python only checks the keys.
If the dictionary is empty, all() returns True.

print(all({0: False, 1: True}))
print(all({1: False, 2: True}))
print(all({"a_key": "a value"}))
print(all({}))

Output

False
True
True
True

Sets

Sets work similar to lists and tuples.
If the set is empty, True is returned.

print(all({False, False, False}))
print(all({False, True, False}))
print(all({1, 2, 3}))
print(all({1, 0, 2}))
print(all({}))

Output

False
False
True
False
True

Conclusion

This post showed you how to check if all elements are True in an iterable using the all() function in Python.
In particular we have seen examples for the most common iterables that are lists, tuples, strings, dictionaries and sets.

I hope this post was useful to you and I invite you to ask in the comments below if you have any doubts or if you are in trouble.

Leave a Comment

Your email address will not be published. Required fields are marked *