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 a 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))
Examples
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 a 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 a filter:
You can achieve the same results using a filter:
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']