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
Use the all() function to check if all items in a list are None in Python, e.g. if all(i is None for i in my_list): . The all() function takes an iterable as an argument and returns True if all of the elements in the iterable are truthy (or the iterable is empty).
Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.
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')
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With