Remove empty strings from a list of strings


Question

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?

1
600
5/26/2019 3:19:22 PM

Accepted Answer

I would use filter:

str_list = filter(None, str_list) # fastest
str_list = filter(bool, str_list) # fastest
str_list = filter(len, str_list)  # a bit slower
str_list = filter(lambda item: item, str_list) # slower than list comprehension

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

str_list = list(filter(None, str_list)) # fastest

(etc.)

Tests:

>>> timeit('filter(None, str_list)', 'str_list=["a"]*1000', number=100000)
2.4797441959381104
>>> timeit('filter(bool, str_list)', 'str_list=["a"]*1000', number=100000)
2.4788150787353516
>>> timeit('filter(len, str_list)', 'str_list=["a"]*1000', number=100000)
5.2126238346099854
>>> timeit('[x for x in str_list if x]', 'str_list=["a"]*1000', number=100000)
13.354584932327271
>>> timeit('filter(lambda item: item, str_list)', 'str_list=["a"]*1000', number=100000)
17.427681922912598
1009
2/17/2018 7:16:25 PM

List comprehensions

strings = ["first", "", "second"]
[x for x in strings if x]

Output: ['first', 'second']

Edit: Shortened as suggested


Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow
Icon