Check if all items in a list are None in Python

avatar

Borislav Hadzhiev

Wed Jun 15 20222 min read

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 items in a 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 as an argument 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, we can conclude that the list contains only None values.

Use the search field on my Home Page to filter through my more than 1,000 articles.