Remove empty strings from list of strings in Python
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:
|
1 2 3 4 5 6 |
if __name__ == '__main__': l = ['A', 'B', '', 'C', '', 'D'] l = list(filter(None, l)) print(l) # ['A', 'B', 'C', 'D'] |
You can also pass the len function to filter the empty strings from a list, as shown below:
|
1 2 3 4 5 6 |
if __name__ == '__main__': l = ['A', 'B', '', 'C', '', 'D'] l = list(filter(len, l)) print(l) # ['A', 'B', 'C', 'D'] |
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.
|
1 2 3 4 5 6 |
if __name__ == '__main__': l = ['A', 'B', '', 'C', '', 'D'] l = [s for s in l if s] print(l) # ['A', 'B', 'C', 'D'] |
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.
|
1 2 3 4 5 6 |
if __name__ == '__main__': l = ['A', 'B', '', 'C', '', 'D'] l = ' '.join(l).split() print(l) # ['A', 'B', 'C', 'D'] |
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:
|
1 2 3 4 5 6 7 8 9 10 11 12 |
if __name__ == '__main__': l = ['A', 'B', '', 'C', '', 'D'] try: while True: l.remove("") except ValueError: pass print(l) # ['A', 'B', 'C', 'D'] |
That’s all about removing empty strings from the list of strings in Python.
Thanks for reading.
To share your code in the comments, please use our online compiler that supports C, C++, Java, Python, JavaScript, C#, PHP, and many more popular programming languages.
Like us? Refer us to your friends and support our growth. Happy coding :)