Remove empty strings from a list of strings Remove empty strings from a list of strings python python

Remove empty strings from a list of strings


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))


Using a list comprehension is the most Pythonic way:

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

If the list must be modified in-place, because there are other references which must see the updated data, then use a slice assignment:

strings[:] = [x for x in strings if x]


filter actually has a special option for this:

filter(None, sequence)

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, ...)


matomo