A list is a data structure that stores multiple objects or variables in a single variable. Let’s say you have a list that contains some empty strings in it. Then how you will remove them? In this post, you will learn how to remove empty strings from list in python using various methods.
Method to remove Empty Strings from List in Python
Let’s learn all the methods to remove empty strings from the list.
Method 1: Use a list comprehension
You can use the list comprehension to remove the empty strings from the list.
my_list = ['A', '', 'B', '', 'C', '']
new_list = [item for item in my_list if item != '']
print(new_list)
This approach allows you to create a new list (new_list) by iterating over the original list (my_list
). Then after you append only non-empty strings to the new list.
Method 2: Using the filter() function
The second method to remove the empty strings is the use of a filter function.
my_list = ['A', '', 'B', '', 'B', '']
new_list = list(filter(lambda item: item != '', my_list))
print(new_list)
Here, the filter()
function filters out the empty strings by using a lambda function. After that check if each item is not equal to an empty string.
Method 3: Using a loop
You can also use the basic loop to clear out the empty strings from a particular list.
my_list = ['A', '', 'B', '', 'B', '']
new_list = []
for item in my_list:
if item != '':
new_list.append(item)
print(new_list)
This method iterates over each item in the list and appends non-empty strings to a new list.
Method 4: Using list comprehension with the bool() function
my_list = ['A', '', 'B', '', 'B', '']
new_list = [item for item in my_list if bool(item)]
print(new_list)
By using the bool()
function in the condition of the list comprehension, empty strings are treated as False, and non-empty strings are treated as True. Thus it effectively removes the empty strings from the list.
Method 5: Using the strip() method
my_list = ['A', ' ', 'B', ' ', 'B', '']
new_list = [item for item in my_list if item.strip()]
print(new_list)
The strip()
method is used here to remove any leading or trailing whitespace from each string. If the result is a non-empty string, it is included in the new list.
Method 6: Using a while loop:
my_list = ['A', '', 'B', '', 'B', '']
new_list = my_list.copy()
while '' in new_list:
new_list.remove('')
print(new_list)
This method creates a copy of the original list and repeatedly removes empty strings until none remain.
In each method, the output will be as below.
['A', 'B', 'C']
Conclusion
It’s better that you should remove the empty string from the list. The above methods will allow you to remove the empty strings from the list. You can use any method you want or are comfortable with.
Leave a Reply