Check if all list elements satisfy a condition in Python

avatar

Borislav Hadzhiev

Last updated: Aug 13, 2022

banner

Photo from Unsplash

Check if all list elements satisfy a condition in Python #

Use the all() function to check if all elements in a list satisfy a condition, e.g. if all(item > 10 for item in my_list):. The all() function will return True if all of the elements in the list meet the condition and False otherwise.

main.py
my_list = [13, 25, 30] if all(item > 10 for item in my_list): # 👇️ this runs print('All elements in the list are greater than 10') else: print('All elements in the list are less than 10') # 👇️ True print(all(item > 10 for item in my_list)) # 👇️ False print(all(item > 1000 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 list item is greater than 10 and return the result.

You can use this approach to check for any other condition.

Here is an example that checks if all elements in the list are None.

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

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).

If any of the values in the list doesn't meet the condition, the all() function will short-circuit returning False.

Note that the all() function returns True for any condition if the provided iterable is empty.

Here is an example that checks if all elements in the list are integers.

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

If you need to handle the scenario where the list is empty, check for the list's length.

main.py
my_list = [] if len(my_list) > 0 and all(isinstance(item, int) for item in my_list): print('All elements in the list are integers') else: print('Not all elements in the list are integers')

We used the and boolean operator, so for the if block to run, both conditions have to be met.

The list's length is not greater than 0, so the else block runs.

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.