How to remove empty string from list in Python

There are several approaches that you can use to remove empty strings from your python List. Here are all the approaches with examples:

1. Using List Comprehension

Python
original_list = ["apple", "", "banana", "", "cherry"]
filtered_list = [item for item in original_list if item != ""]
print(filtered_list)  
# Output: ['apple', 'banana', 'cherry']

2. Using the filter() Function

Python
original_list = ["apple", "", "banana", "", "cherry"]
filtered_list = list(filter(lambda x: x != "", original_list))
print(filtered_list)  
# Output: ['apple', 'banana', 'cherry']

3. Using if condition in a for loop

Python
original_list = ["apple", "", "banana", "", "cherry"]
filtered_list = []
for item in original_list:
    if item != "":
        filtered_list.append(item)
print(filtered_list)  
# Output: ['apple', 'banana', 'cherry']

4. Using remove() method ( Returns Modified Original List )

Python
original_list = ["apple", "", "banana", "", "cherry"]
original_list = [item for item in original_list if item != ""]
print(original_list)  
# Output: ['apple', 'banana', 'cherry']

Leave a Reply

Your email address will not be published. Required fields are marked *