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(\'\')
Depending on the size of your list, it may be most efficient if you use list.remove() rather than create a new list:
l = ["1", "", "3", ""]
while True:
try:
l.remove("")
except ValueError:
break
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).