How to Remove Empty Strings from List in Python?
I want to remove all empty strings from a list of strings in Python. My current approach is as follows:
while '' in str_list:
str_list.remove('')
Is there a more Pythonic way to remove empty strings from list Python?
Hey All!
A concise and efficient way to remove empty strings from a list is by using list comprehension. It filters out unwanted elements in a single line.
str_list = ["a", "", "b", "", "c"]
str_list = [s for s in str_list if s]
print(str_list) # Output: ['a', 'b', 'c']
This approach checks each element and keeps only non-empty strings, making it both fast and readable. If you’re dealing with a more complex scenario, such as processing data in parallel using a python multiprocessing queue
, you could use this same technique within worker processes to clean up lists more efficiently.
Using filter()
Another clean and readable way to remove empty strings is by using the built-in filter()
function. This method is simple and expressive, and it’s ideal when you want a one-liner solution.
str_list = ["a", "", "b", "", "c"]
str_list = list(filter(bool, str_list))
print(str_list) # Output: ['a', 'b', 'c']
The filter(bool, ...)
function removes all ‘falsy’ values, including empty strings. This can be especially useful when working with large data sets, such as when you’re processing a list in a python multiprocessing queue
. You can apply this filter inside worker processes to speed up the cleaning of lists in parallel tasks.
Hey All!
Using a Loop with Conditional Assignment
If you prefer a more explicit and easy-to-understand approach, you can use a loop with conditional checks to rebuild the list. This is an especially good option for beginners or when you need more control over the filtering process.
str_list = ["a", "", "b", "", "c"]
str_list = [s for s in str_list if s != ""]
print(str_list) # Output: ['a', 'b', 'c']
This method explicitly compares each element with an empty string and excludes it. When dealing with large lists, or when processing multiple lists simultaneously, you might even consider using this method in combination with python multiprocessing queue
to ensure that each worker handles its own filtering efficiently.