pythonlistpython-2.7

Removing sublists of empty entries from a list


I've got a list that looks like this:

some_list = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h'], ['', '', '', '']]

I want to remove all empty sublists within the list, so that the product is just

clean_list = [['a', 'b', 'c', 'd'], ['e', 'f', 'g', 'h']]

I've tried the following

for x in some_list:
    if x == ['', '', '', '']:
        some_list.remove(x)

and

clean_list = filter(None, list)

and

clean_list = [x for x in list if x]

but I keep getting an output with sublists with empty entries. Thoughts?


Solution

  • Use the any() function to select lists with non-empty values:

    clean_list = [sublist for sublist in some_list if any(sublist)]
    

    any() short-circuits; iterating over the values in sublist it'll return True as soon as it finds a true (non-empty) string in that sublist, and only returns False after testing all values, finding them to be empty.

    Your x == ['', '', '', ''] loop failed because you were modifying a list while iterating over it. As the list gets shorter, iteration starts skipping later elements as they have shifted indices, see strange result when removing item from a list for more detail.

    Your filter(None, ..) attempt fails because ['', '', '', ''] is itself not a false value, it is a non-empty list, there are 4 strings in it. It doesn't matter that those strings are empty. The same applies to your list comprehension; all lists in some_list are non-empty, so all are considered true.