Check if any item in a list is None using Python

avatar

Borislav Hadzhiev

Wed Jun 15 20222 min read

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

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