Most concise way to check whether a list is empty or contains only 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
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')
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
You can directly compare lists with ==
:
if x == [None,None,None]:
if x == [1,2,3]
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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.