Python: How to check if a nested list is essentially empty?

Viewed 27127

Is there a Pythonic way to check if a list (a nested list with elements & lists) is essentially empty? What I mean by empty here is that the list might have elements, but those are also empty lists.

The Pythonic way to check an empty list works only on a flat list:

alist = []
if not alist:
    print("Empty list!")

For example, all the following lists should be positive for emptiness:

alist = []
blist = [alist]               # [[]]
clist = [alist, alist, alist] # [[], [], []]
dlist = [blist]               # [[[]]]
9 Answers
def isEmpty(a):
    return all(map(isEmpty,a)) if isinstance(a, list) else False

Simply.

If you want to check if the nested list has no item in it, you can use a Depth First Search (DFS) traversing method like this

def is_list_empty(values: list):
    
    if len(values) == 0:
        return True

    res = []
    for val in values:
        if isinstance(val, list):
            res.append(is_list_empty(val))
        else:
            res.append(False)
    
    return all(res)

v_list = [ [], [[1, 2], [], []], []]
is_list_empty(v_list)  # False, as there are two times in it.
v_list = [ [], [[], [], []], []]
is_list_empty(v_list)  # True, in fact ther is no item in it.

This is similar to @AshwinNanjappa's answer but it is easier to understand.

It is possible to check if a list of lists is empty or not by using len function to check if the list's length equal to zero or not, then use any to give True if there is any True (There is at least one empty sublist), as shown:

def empty(lis):
    # True if there is an empty sublist
    x = [True for i in lis if len(i) == 0]
    # any function will return True if at least there is one True in x
    if any(x):
        print("There is an empty sublist!!")
    else:
        print("There is no any empty sublist")
        
lis = [[1,2,3],[3],[2]]
empty(lis)
# The output is: There is no any empty sublist
lis2 = [[1,2,3],[],[]]
empty(lis2)
# The output is: There is an empty sublist!!
Related