Nick
Nick

Reputation: 27

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?

Upvotes: 0

Views: 911

Answers (2)

This answer is for a different intepretation of your question: when we want to remove all falsy values from sublists, and remove sublists that end up empty:

clean_list = [clean_sublist for sublist in some_list if (clean_sublist:=[x for x in sublist if x])]

For the example provided, this will behave the same way as the accepted answer. The behavior will differ when we have sublists containing both truthy and falsy values.

Upvotes: 0

Martijn Pieters
Martijn Pieters

Reputation: 1121148

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.

Upvotes: 3

Related Questions