Python: How to check if a nested list is essentially empty?
Use the any()
function. This returns True
if any list within the list is not empty.
alist = [[],[]]
if not any(alist):
print("Empty list!")
>> Empty list!
see: https://www.programiz.com/python-programming/methods/built-in/any
I have combined the use of isinstance()
by Ants Aasma and all(map())
by Stephan202, to form the following solution. all([])
returns True
and the function relies on this behaviour. I think it has the best of both and is better since it does not rely on the TypeError
exception.
def isListEmpty(inList):
if isinstance(inList, list): # Is a list
return all( map(isListEmpty, inList) )
return False # Not a list
Simple code, works for any iterable object, not just lists:
>>> def empty(seq):
... try:
... return all(map(empty, seq))
... except TypeError:
... return False
...
>>> empty([])
True
>>> empty([4])
False
>>> empty([[]])
True
>>> empty([[], []])
True
>>> empty([[], [8]])
False
>>> empty([[], (False for _ in range(0))])
True
>>> empty([[], (False for _ in range(1))])
False
>>> empty([[], (True for _ in range(1))])
False
This code makes the assumption that anything that can be iterated over will contain other elements, and should not be considered a leaf in the "tree". If an attempt to iterate over an object fails, then it is not a sequence, and hence certainly not an empty sequence (thus False
is returned). Finally, this code makes use of the fact that all
returns True
if its argument is an empty sequence.