Python - find length of sublists in a list, ignoring empty entries

Viewed 2586

So it's easy enough to determine the length of the sublists of a list with:

list_length = [len(w) for w in data]

But is there a way to get the length while ignoring any empty list entries: ''?

I have a list of lists, [data], and one of the sublists looks like this:

['GOM COD', '60', '$2.00', '', '$120.00']

So list_length is determined to be 5. Until now, I would then turn the list of lists into a single list in order to remove all '' entries, and then turn it back into a list of lists based on whatever value list_length is. In this case, however, after the removal of all ''s, the list_length value of 5 ends up being incorrect and creates a messy DataFrame.

I do try to remove all empty string entries with data = list(filter(None, data)) but that removes only those sublists that are made up entirely of ''.

So I would like to ultimately be able to determine the length of a sublist while ignoring or excluding ''s, because I have to run this code on many files so it has to be robust enough to read a correct list_length.

Is what I'm asking possible? Or even the smartest approach to this?

Thanks.

2 Answers
Related