Discover more from Just Emil Kirkegaard Things
Python: Removing empty lists from mixed nested lists
Suppose you have some function that returns possibly nested lists with empty lists inside. Worse, they may have lists with lists with an empty list inside. And suppose you want to get rid of all the empty lists, including those that just have other lists with empty lists inside. Like this:
a = [1, [2, ], , "a", []]
I came up with the following pair of functions to get rid of these:
#meta function def remove_empty_lists(l): keep_going = True prev_l = l while keep_going: #call remover on the list new_l = remover(prev_l) #are they identical objects? if new_l == prev_l: keep_going = False #set prev to new prev_l = new_l #return the result return new_l #function def remover(l): #new list newlist =  #loop over elements for i in l: #pdb.set_trace() #is element a non-empty list? then call self on it if isinstance(i, list) and len(i) != 0: newlist.append(remover(i)) #if not a list if not isinstance(i, list): newlist.append(i) #return newlist return newlist
>>> remover(a) [1, , 'a', ] >>> remove_empty_lists(a) [1, , 'a']
The first only runs thru the elements once and thus neglects to rid rid of the second-order empty list at the end. The second function keeps removing empty lists until the function no longer has an effect and the process comes to a halt.
I have no idea no fast this is compared to other methods, but it gets the job done!