Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

python

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.

like image 961
Bryan Avatar asked Mar 03 '15 16:03

Bryan


People also ask

How do I check if a none is in a list 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 .

Is none and 0 same in Python?

None is not the same as 0, False, or an empty string. None is a data type of its own (NoneType) and only None can be None.

How do I check if a list Isempty?

In this solution, we use the len() to check if a list is empty, this function returns the length of the argument passed. And given the length of an empty list is 0 it can be used to check if a list is empty in Python.


1 Answers

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) 
like image 129
Martijn Pieters Avatar answered Oct 15 '22 13:10

Martijn Pieters