How to Remove all Empty Strings from a List of Strings in Python

Created
Modified

Using filter Function

The filter(function, iterable) function constructs an iterator from those elements of iterable for which function returns true.

The following example:

#!/usr/bin/python3

a = ["a", "", " ", "c", " "]

# b = list(filter(bool, a))
# b = list(filter(len, a))
b = list(filter(None, a))
print(b)

b = list(filter(str.strip, a))
print(b)
['a', ' ', 'c', ' ']
['a', 'c']

Using List Comprehension

Using a list comprehension is the most Pythonic way:

#!/usr/bin/python3

a = ["a", "", " ", "c", " "]

b = [x for x in a if x.strip()]
print(b)
['a', 'c']

Using join Method

The following example should cover whatever you are trying to do:

#!/usr/bin/python3

a = ["a", "", " ", "c", " "]

b = ' '.join(a).split()
print(b)
['a', 'c']

Related Tags