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

Alan Gauld alan.gauld at yahoo.co.uk
Wed Nov 17 18:01:57 EST 2021


On 17/11/2021 13:51, Pascal Maniriho wrote:
> Dear all,
> 
> I have the following list in Python and would like to remove all empty
> elements without invalidating indices.

I don;t know what you mean by the last comment.
If you remove elements it must affect the indices,
there is no way to avoid that.

> 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))

First you need to realize that you actually have a list of lists
so you will need a loop. Also to change the embedded lists in
the loop you will need the index which you can get from the
enumerate() function.

Something like:

for index,sublist in mylist:
    mylist[index] = [item for item in sublist if item]

should work.

However, one other query remains. In your example of output you only
have two sublists. Why is the third not included? Is that deliberate?
If so, slicing could remove the last list.

-- 
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/
http://www.amazon.com/author/alan_gauld
Follow my photo-blog on Flickr at:
http://www.flickr.com/photos/alangauldphotos




More information about the Tutor mailing list