Check if all values in list are less than certain number in Python

avatar

Borislav Hadzhiev

Last updated: Aug 11, 2022

banner

Photo from Unsplash

Check if all values in list are less than certain number in Python #

Use the all() function to check if all values in a list are less than a certain number, e.g. if all(item < 50 for item in my_list):. The all() function will return True if all of the values in the list are less than the specified number and False otherwise.

main.py
my_list = [3, 9, 14, 27, 38] if all(item < 50 for item in my_list): # 👇️ this runs print('All values in the list are less than 50') else: print('Not all values in the list are less than 50') # 👇️ True print(all(item < 50 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 less than the specified number 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).

If any of the values in the list is not less than the specified value, the all() function will short-circuit returning False.

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

main.py
my_list = [] if all(item < 50 for item in my_list): # 👇️ this runs print('All values in the list are less than 50') else: print('Not all values in the list are less than 50') # 👇️ True print(all(item < 50 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(item < 50 for item in my_list): print('All values in the list are less than 50') else: # 👇️ this runs print('Not all values in the list are less than 50')

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.