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?
List comprehensions
Output:
['first', 'second']
Edit: Shortened as suggested
Depending on the size of your list, it may be most efficient if you use list.remove() rather than create a new list:
This has the advantage of not creating a new list, but the disadvantage of having to search from the beginning each time, although unlike using
while '' in l
as proposed above, it only requires searching once per occurrence of''
(there is certainly a way to keep the best of both methods, but it is more complicated).filter(None, str)
does not remove empty strings with a space ' ', it only prunes away '' and ' '.join(str).split()
removes both. but if your element of list having space then it will change your list elements also because it's joining first your all elements of list then spiting them by space so You should use : -It will remove both and won't effect your elements also Like :-
output:-
['hello', 'world', 'ram'] <-------------- output of
' '.join(lstr).split()
['hello', 'world ram']
Short and sweet.
Reply from @Ib33X is awesome. If you want to remove every empty string, after stripped. you need to use the strip method too. Otherwise, it will return the empty string too if it has white spaces. Like, " " will be valid too for that answer. So, can be achieved by.
The answer for this will be
["first", "second"]
.If you want to use
filter
method instead, you can do likelist(filter(lambda item: item.strip(), strings))
. This is give the same result.To eliminate empties after stripping:
Some PROs:
fast, selectively using builtins and comprehensions.