This post will discuss how to remove empty strings from the list of strings in Python.

1. Using filter() function

The recommended solution is to use the built-in function filter(function, iterable), which constructs an iterator from elements of an iterable for which the specified function returns true. If the function is None, the identity function is assumed, i.e., all elements of iterable that are false are removed. Here’s a working example using filters:

Download  Run Code

 
You can also pass the len function to filter the empty strings from a list, as shown below:

Download  Run Code

2. Using List Comprehension

You can also use list comprehension to remove empty strings from a list of strings. A list comprehension consists of an expression, followed by a for-loop, followed by an optional for-loop or if statement, all enclosed within the square brackets []. Note that this solution is slower than the filter approach.

Download  Run Code

3. Using join() with split() function

The expression ' '.join(iterable).split() can be used to filter empty values from an iterable. ' '.join(list) efficiently concatenate the list of strings delimited by a space. Then split() function is called upon the resultant string, which returns a list of the strings where consecutive whitespace are regarded as a single separator.

Download  Run Code

4. Using list.remove() function

The list.remove("") only removes the first occurrence of an empty string from the list. To remove all occurrences of an empty string from a list, you can take advantage of the fact that it raises a ValueError when it can’t find the specified item in the list. The idea is to repeatedly call remove() function until it raises a ValueError exception. This is demonstrated below:

Download  Run Code

That’s all about removing empty strings from the list of strings in Python.