[Tutor] How to remove all empty elements from a list of list

Mats Wichmann mats at wichmann.us
Wed Nov 17 19:21:52 EST 2021


On 11/17/21 06:51, Pascal Maniriho wrote:
> Dear all,
> 
> I have the following list in Python and would like to remove all empty
> elements without invalidating indices.
> 
> mylist = [['write', 'create', 'draw', 'book', 'mkay', '', '', '', '', '',
> ''], ['hey', 'mykey', 'ange', 'kiki', 'rose', '', '', '', '', '', '', '',
> '', '', ''],['name','age','address', 'nationality', '', '', '', '', '', '',
> '', '', '', '', '', '']]
> 
> I need the output like this:
> 
> mylist = [['write', 'create', 'draw', 'book', 'mkay'], ['hey', 'mykey',
> 'ange', 'kiki', 'rose']]
> 
> I have tried to use the following line of code, but it does not give the
> expected output.
> 
> mylist1 = list(filter(None, mylist))

It's an interesting problem, and stating it correctly is important as 
far as picking solutions.

There are no empty elements in mylist so from your problem statement 
there is nothing to remove.

There are clearly empty elements in the members of mylist, so you have 
to work a level down (see Alan's reply).

It's often a problem when you try to modify a list while looping over 
it, for which the solution is to loop over a copy so it's safe to delete 
items from the original. But... your try creates a new list anyway, so 
it doesn't seem you have to do modify-in-place (we can't fully guess 
your requirements unless you tell us).

 From the nature of the data, here's a random thought:  this seems to 
have come from somewhere that probably wasn't originally a Python list - 
perhaps processing a text or csv file or some such.  Is it possible it's 
better to strip out trailing blanks - in this example they're all 
trailing, but again, what are the real requirements? - *before* 
converting to a list? That might even be a cleaner way.



More information about the Tutor mailing list