Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove empty strings from a list of strings

I want to remove all empty strings from a list of strings in python.

My idea looks like this:

while '' in str_list:     str_list.remove('') 

Is there any more pythonic way to do this?

like image 688
zerodx Avatar asked Oct 02 '10 11:10

zerodx


1 Answers

I would use filter:

str_list = filter(None, str_list) str_list = filter(bool, str_list) str_list = filter(len, str_list) str_list = filter(lambda item: item, str_list) 

Python 3 returns an iterator from filter, so should be wrapped in a call to list()

str_list = list(filter(None, str_list)) 
like image 117
livibetter Avatar answered Sep 19 '22 13:09

livibetter