Check if any item in a list is None using Python

avatar

Borislav Hadzhiev

Last updated: Jun 15, 2022

banner

Photo from Unsplash

Check if any item in a list is None using Python #

Use the in operator to check if any item in a list is None, e.g. if None in my_list:. The in operator tests for membership. For example, x in l evaluates to True if x is a member of l, otherwise it evaluates to False.

main.py
my_list = ['a', 'b', None, 'c'] # ✅ check if any item in the list is None if None in my_list: # 👇️ this runs print('There is a None value in the list') # ✅ check if all items in the list are None (or list is empty) if all(i is None for i in my_list): print('all items in the list are None')

The first if statement checks if any item in the list is None, and the second - if the list only contains None values.

The in operator tests for membership.

main.py
my_list = ['a', 'b', None, 'c'] print(None in my_list) # 👉️ True print('hello' in my_list) # 👉️ False

x in l evaluates to True if x is a member of l.

x not in l returns the negation of x in l.

Alternatively, you can use the any() function.

main.py
my_list = ['a', 'b', None, 'c'] if any(item is None for item in my_list): # 👇️ this runs print('list contains a None value')

The any function takes an iterable as an argument and returns True if any element of the iterable is truthy.

main.py
my_list = ['a', 'b', None, 'c'] # 👇️ True print(any(item is None for item in my_list))

If the iterable is empty or none of the elements in the iterable are truthy, the any function returns False.

We passed a generator expression to the any() 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 at least once, the any() function will return True.

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.