Check if any item in Python list is None (but include zero)

Python

Python Problem Overview


I'm trying to do a simple test that returns True if any of the results of a list are None. However, I want 0 and '' to not cause a return of True.

list_1 = [0, 1, None, 4]
list_2 = [0, 1, 3, 4]

any(list_1) is None
>>>False
any(list_2) is None
>>>False

As you can see, the any() function as it is isn't being helpful in this context.

Python Solutions


Solution 1 - Python

For list objects can simply use a membership test:

None in list_1

Like any(), the membership test on a list will scan all elements but short-circuit by returning as soon as a match is found.

any() returns True or False, never None, so your any(list_1) is None test is certainly not going anywhere. You'd have to pass in a generator expression for any() to iterate over, instead:

any(elem is None for elem in list_1)

Solution 2 - Python

list_1 = [0, 1, None, 4]

list_2 = [0, 1, 3, 4]

any(x is None for x in list_1)
>>>True

any(x is None for x in list_2)
>>>False

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBryanView Question on Stackoverflow
Solution 1 - PythonMartijn PietersView Answer on Stackoverflow
Solution 2 - PythonTom CornebizeView Answer on Stackoverflow