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

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?


Solution 1:

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.

Solution 2:

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.

Solution 3:

Since Match objects are never going to evaluate to false, it's ok and much faster to just use not any(L)

$ python -m timeit -s"L=[None,None,None]" "all( v is None for v in L )"
100000 loops, best of 3: 1.52 usec per loop
$ python -m timeit -s"L=[None,None,None]" "not any(L)"
1000000 loops, best of 3: 0.281 usec per loop

$ python -m timeit -s"L=[None,1,None]" "all( v is None for v in L )"
100000 loops, best of 3: 1.81 usec per loop
$ python -m timeit -s"L=[None,1,None]" "not any(L)"
1000000 loops, best of 3: 0.272 usec per loop

Solution 4:

Or a bit weird but:

a = [None, None, None]
set(a) == set([None])

OR:

if [x for x in a if x]: # non empty list
    #do something   

EDITED:

def is_empty(lVals):
    if not lVals:
        return True
    for x in lVals:
        if x:
            return False
    return True