1

how to check if this list is empty?

l = ['',['']]

I tried solutions from how to find if nested lists are empty. but none of them worked.

def isListEmpty(inList):
    if isinstance(inList, list): # Is a list
         return all( map(isListEmpty, inList) )
    return False # Not a list
Miffy
  • 185
  • 1
  • 15

5 Answers5

1

You should check if the list is falsy/empty first before recursively checking the list items. You can also avoid explicitly returning True or False by using the and and or operators:

def isListEmpty(inList):
    return inList == '' or isinstance(inList, list) and (not inList or all(map(isListEmpty, inList)))

Demo: https://repl.it/repls/AccurateSmallOutcome

blhsing
  • 91,368
  • 6
  • 71
  • 106
0

For lists that actually are empty, the function should simply return True.

def isListEmpty(inList):
    if isinstance(inList, list): # Is a list
        if len(inList) == 0:
            return True
        else:
            return all(map(isListEmpty, inList))
    return False # Not a list
John Gordon
  • 29,573
  • 7
  • 33
  • 58
0

l is not empty in fact. But in this case this code should work:

l = ['',['']]
def isListEmpty(inList):
    for char in inList:   
        if char == '' or ['']:
            return True
        else:
            return False
            break

print(isListEmpty(l))
Heyran.rs
  • 501
  • 1
  • 10
  • 20
  • What about for deeper lists like `['',['',['']]]` ? That is why other people have taken a recursive approach, because it can be infinitely deep – Adam Dadvar Feb 14 '19 at 17:26
0

You can use a simple recursive approach with any. Using any would make sure that the recursively search ends as soon as a non empty item is found

>>> def is_non_empty_list (l):
...     return any(is_non_empty_list(e) if isinstance(e, list) else e for e in l)
... 
>>> def is_empty_list (l):
...     return not is_non_empty_list(l)
... 
>>> is_empty_list(['', ['']])
True
>>> is_empty_list(['', ['a']])
False
>>> 
Sunitha
  • 11,777
  • 2
  • 20
  • 23
-1

Try This

l = [' ',[ ]]
def isListEmpty(thisList):
  for el in thisList:
    if (len(el)==0 and type(el)==list):
      print('empty') # Or whatever you want to do if you encounter an empty list

isListEmpty(l)

If you face any problems comment below

anand_v.singh
  • 2,768
  • 1
  • 16
  • 35