In this article we will discuss different ways to check if a list contains only None or not.

Suppose we have a list,

Now we want to confirm that all items in this list are None. There are different ways to do that. Let’s discuss them one by one,

Check if a list contains only None using for loop

The first solution that comes to our mind is using for loop.
Logic is, Iterate over all the items of a list using for loop and for each item check if it is None or not. As soon as a non None item is found, break the loop because it means all items of list are not None. Whereas, if the loop ends and not even a single non None item is found, then it proves that all items of the list are None.

Let’s create a function that accepts a list and check if all items are none or not using the above logic,

Use this function to check if all items in list are None,

Output:

Generic function to check if all items in list matches a given item like None

In the above example, we created a separate function just to check if all items in a list are None or not, although it does the work but it is not a reusable function. So, let’s create a generic function to check if all items of a list are same and also matches the given element,

This function accepts a list and an item as an argument. Then checks if all items in the given list matches the given item using the same logic as previous example. We can use this function to check if all items of list are None,

Output:

Now we can use this function at other places too like, to confirm if all elements in a list matches the given number or string etc.

Check if a list contains only None using List comprehension

Let’s look at a pythonic way to confirm if all items in a list are None,

Let’s use this function to check all items of list are None,

Output:

It is a one line solution.
Using list comprehension we created a Boolean list from the existing list. Each element in this bool list corresponds to an item for the main list. Basically, in the List Comprehension we iterated over the given list and for each element we checked if it is None or not. If it is None then added True in the bool list else added False. Now using all() checked if the bool list contains only True or not. If all() function returns True, then it means our main list contains only None.

We can use this function in a generic way too. For example check if all items in the list matches a given string,

Output:

The complete example is as follows,

Output:

Python Recommendations:

C++ & C++11 Recommendations:

If you didn't find what you were looking, then do suggest us in the comments below. We will be more than happy to add that.

Subscribe with us to join 1500+ Python & C++ developers, to get more Tips &  Tutorials like this.