Python List – How to Check for Empty Elements in a List

listpythonpython-2.7

Suppose I have a empty string, it will be split:

>>>''.split(',')
['']

The result of the split is ['']. I use bool to check it whether or not it's empty. It will return True.

>>>bool([''])
True

How do I check the split result is empty?

Best Answer

With bool(['']) you're checking if the list [''] has any contents, which it does, the contents just happen to be the empty string ''.

If you want to check whether all the elements in the list aren't 'empty' (so if the list contains the string '' it will return False) you can use the built-in function all():

all(v for v in l)

This takes every element v in list l and checks if it has a True value; if all elements do it returns True if at least one doesn't it returns False. As an example:

l = ''.split(',')

all(v for v in l)
Out[75]: False

You can substitute this with any() to perform a partial check and see if any of the items in the list l have a value of True.

A more comprehensive example* with both uses:

l = [1, 2, 3, '']

all(l)
# '' doesn't have a True value
Out[82]: False

# 1, 2, 3 have a True value
any(l)
Out[83]: True

*As @ShadowRanger pointed out in the comments, the same exact thing can be done with all(l) or any(l) since they both just accept an iterable in the end.