Here are 4 ways to remove empty strings from a list in Python:
(1) Using a list comprehension:
new_list = [x for x in list_with_empty_strings if x != '']
(2) Using for loop:
new_list = [] for x in list_with_empty_strings: if x != '': new_list.append(x)
(3) Using filter:
new_list = list(filter(None, list_with_empty_strings))
(4) Using filter and lambda:
new_list = list(filter(lambda x: x != '', list_with_empty_strings))
Next, you’ll see how to apply each of the above approaches using simple examples.
Examples of removing empty strings from a list in Python
Case 1: Using a list comprehension
Suppose that you have the following list that contains empty strings:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] print(list_with_empty_strings)
As you can see, there are currently 3 empty strings in the list (as highlighted in yellow):
['blue', 'green', '', 'red', '', 'yellow', 'orange', '']
The goal is to remove those 3 empty strings from the list in Python.
You can then use a list comprehension to remove those empty strings:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = [x for x in list_with_empty_strings if x != ''] print(new_list)
The empty strings would now be removed:
['blue', 'green', 'red', 'yellow', 'orange']
Case 2: Using for loop
Alternatively, you can use a for loop to remove the empty strings:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = [] for x in list_with_empty_strings: if x != '': new_list.append(x) print(new_list)
You’ll get the same list without the empty strings:
['blue', 'green', 'red', 'yellow', 'orange']
(3) Using filter:
You can achieve the same results using a filter as follows:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = list(filter(None, list_with_empty_strings)) print(new_list)
As before, you’ll get the same list without the empty strings:
['blue', 'green', 'red', 'yellow', 'orange']
(4) Using filter and lambda:
Finally, you may apply a filter and lambda to remove the empty strings in the list:
list_with_empty_strings = ['blue', 'green', '', 'red', '', 'yellow', 'orange', ''] new_list = list(filter(lambda x: x != '', list_with_empty_strings)) print(new_list)
The result:
['blue', 'green', 'red', 'yellow', 'orange']