Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if all items in the list are None?

Tags:

python

In [27]: map( lambda f,p: f.match(p), list(patterns.itervalues()), vatids ) Out[27]: [None, <_sre.SRE_Match object at 0xb73bfdb0>, None] 

The list can be all None or one of it is an re.Match instance. What one liner check can I do on the returned list to tell me that the contents are all None?

like image 355
Frankie Ribery Avatar asked Jun 29 '11 09:06

Frankie Ribery


People also ask

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.

How do you check if all elements in a list are numbers?

The 'all' operator is used to check if every element is a digit or not. This is done using the 'isdigit' method. The result of this operation is assigned to a variable.


2 Answers

all(v is None for v in l) 

will return True if all of the elements of l are None

Note that l.count(None) == len(l) is a lot faster but requires that l be an actual list and not just an iterable.

like image 77
Dan D. Avatar answered Sep 27 '22 01:09

Dan D.


not any(my_list) 

returns True if all items of my_list are falsy.

Edit: Since match objects are always truthy and None is falsy, this will give the same result as all(x is None for x in my_list) for the case at hand. As demonstrated in gnibbler's answer, using any() is by far the faster alternative.

like image 30
Sven Marnach Avatar answered Sep 27 '22 01:09

Sven Marnach