Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most concise way to check whether a list is empty or contains only None?

Tags:

python

types

list

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
like image 207
Phillip B Oldham Avatar asked Aug 13 '09 09:08

Phillip B Oldham


People also ask

How do I check if a list contains only None in Python?

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).

Does an empty list == None Python?

Usually, an empty list has a different meaning than None ; None means no value while an empty list means zero values.


1 Answers

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')
like image 144
Stephan202 Avatar answered Oct 20 '22 22:10

Stephan202