tags:

views:

225

answers:

4

Most concise way to check whether a list is empty or [None]?

I understand that I can test:

if MyList:
    pass

and:

if not MyList:
    pass

but what if the list has an item (or multiple items), but those item/s are None:

MyList = [None, None, None]
if ???:
    pass
+2  A: 

If you are concerned with elements in the list which evaluate as true:

if mylist and filter(None, mylist):
    print "List is not empty and contains some true values"
else:
    print "Either list is empty, or it contains no true values"

If you want to strictly check for None, use filter(lambda x: x is not None, mylist) instead of filter(None, mylist) in the if statement above.

Vinay Sajip
+7  A: 

One way is to use all and a list comprehension:

if all(e is None for e in myList):
    print('all empty or None')

This works for empty lists as well. More generally, to test whether the list only contains things that evaluate to False, you can use any:

if not any(myList):
    print('all empty or evaluating to False')
Stephan202
It should be `e is None`.
nikow
That is probably more efficient, yes, but using `==` is not *wrong*.
Stephan202
Small note: The link to all is actually to any...
Mr Shark
Using == *could be* wrong if `type(x).__eq__()` is broken.
ilya n.
@ilya: good point!
Stephan202
@Mr Shark: thanks, fixed.
Stephan202
+7  A: 

You can use the all() function to test is all elements are None:

a = []
b = [None, None, None]
all(e is None for e in a) # True
all(e is None for e in b) # True
unbeknown
+1  A: 

You can directly compare lists with ==:

if x == [None,None,None]:

if x == [1,2,3]
Mark Harrison