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?
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?
Compare time
Notice that
filter(None, lstr)
does not remove empty strings with a space' '
, it only prunes away''
while' '.join(lstr).split()
removes both.To use
filter()
with white space strings removed, it takes a lot more time:Loop through the existing string list and then check for a empty string, if it's not empty populate a new string list with the non-empty values and then replace the old string list with the new string list
filter actually has a special option for this:
It will filter out all elements that evaluate to False. No need to use an actual callable here such as bool, len and so on.
It's equally fast as map(bool, ...)
Use
filter
:The drawbacks of using filter as pointed out is that it is slower than alternatives; also,
lambda
is usually costly.Or you can go for the simplest and the most iterative of all:
this is the most intuitive of the methods and does it in decent time.
Keep in mind that if you want to keep the white spaces within a string, you may remove them unintentionally using some approaches. If you have this list
['hello world', ' ', '', 'hello'] what you may want ['hello world','hello']
first trim the list to convert any type of white space to empty string:
then remove empty string from them list
As reported by Aziz Alto
filter(None, lstr)
does not remove empty strings with a space' '
but if you are sure lstr contains only string you can usefilter(str.strip, lstr)
Compare time on my pc
The fastest solution to remove
''
and empty strings with a space' '
remains' '.join(lstr).split()
.As reported in a comment the situation is different if your strings contain spaces.
You can see that
filter(str.strip, lstr)
preserve strings with spaces on it but' '.join(lstr).split()
will split this strings.