Check if all items in a list are None in Python

avatar

Borislav Hadzhiev

Last updated: Aug 12, 2022

banner

Photo from Unsplash

Check if all items in a list are None in Python #

Use the all() function to check if all items in a list are None in Python, e.g. if all(i is None for i in my_list):. The all() function takes an iterable as an argument and returns True if all of the elements in the iterable are truthy (or the iterable is empty).

main.py
my_list = [None, None, None] # ✅ using all() if all(i is None for i in my_list): # 👇️ this runs print('all items in the list are None') # ✅ using list.count() if my_list.count(None) == len(my_list): # 👇️ this runs print('all items in the list are None')

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

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

If your use case doesn't consider an empty list to contain all None values, you could check for the list's length as well.

main.py
my_list = [None, None, None] # # ✅ using all() if len(my_list) > 0 and all(i is None for i in my_list): # 👇️ this runs print('all items in the list are None')

We passed a generator expression to the all() function.

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

In the example, we check if each item is None and return the result. If the condition is met for all items, the all() function will return True.

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

To check if all values in a list are None:

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

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

main.py
my_list = [None, None, None] print(my_list.count(None)) # 👉️ 3 print(my_list.count('hello')) # 👉️ 0

If the number of None values in the list is the same as the list's length, then the list contains only None 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.