Check if all elements in a list are True in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if all elements in a list are True in Python #

Use the all() function to check if all elements in a list are True, e.g. if all(item is True for item in my_list):. The all() function will return True if all of the values in the list are equal to True and False otherwise.

main.py
my_list = [True, True, True] if all(item is True for item in my_list): # 👇️ this runs print('All list elements are True') else: print('Not all list elements are True') # 👇️ True print(all(item is True for item in my_list))

We used a generator expression to iterate over the list.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current value is equal to True and return the result.

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

main.py
my_list = [True, True, True] # 👇️ True print(all(item is True for item in my_list))

If the all() function finds a value that isn't equal to True, it will short-circuit returning False.

Note that the all() function returns True for any condition if the passed in iterable is empty.
main.py
my_list = [] if all(item is True for item in my_list): # 👇️ this runs print('All list elements are True') else: print('Not all list elements are True') # 👇️ True print(all(item is True for item in my_list))

If you consider an empty list one where not all values are True, check for the list's length.

main.py
my_list = [] if len(my_list) > 0 and all(item is True for item in my_list): print('All list elements are True') else: # 👇️ this runs print('Not all list elements are True')
We used the and boolean operator, so for the if block to run, both conditions have to be met.

The list doesn't have a length greater than 0, so the else block runs.

Alternatively, you can use the list.count() method.

To check if all values in a list are True:

  1. Use the list.count() method to count the True values in the list.
  2. If the number of True values is equal to the list's length, all values in the list are True.
main.py
my_list = [True, True, True] if my_list.count(True) == len(my_list): # 👇️ this runs print('All list elements are True') else: print('Not all list elements are True')

The list.count() method takes a value and returns the number of times the provided value appears in the list.

main.py
my_list = [True, True, True] print(my_list.count(True)) # 👉️ 3

If the number of True values in the list is the same as the list's length, then the list contains only True values.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.