You are currently viewing Python Remove Empty Strings from List

How to remove empty strings from a list in Python? You can use various methods of Python to remove empty strings from a list. Removing empty strings from a list, the resulting list will exclude the empty strings. The empty string(“”) represents a string with no characters.

Advertisements

You can remove empty strings from the list using many ways, for example, by using the remove(), filter(), lambda, list comprehension, enumerate(), for loop, len(), join() + split(), functools.reduce(), itertools.filterfalse(), and filter() with custom functions. In this article, I will explain how to remove empty strings from the list by using all these methods with examples.

1. Quick Examples of Removing Empty Strings from the List

If you are in a hurry, below are some quick examples of removing empty strings from a list.


# Quick examples of removing empty strings from list

# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]

# Example 1: Using remove() method
while("" in mylist):
    mylist.remove("")

# Example 2: Using filter() Method
result = list(filter(None, mylist))

# Example 3: Using filter() and lambda function
result = list(filter(lambda x: x != "", mylist))

# Example 4: Using list comprehension
result = [x for x in mylist if x != ""]

# Example 5: Using list comprehension
result = [i for i in mylist if i]

# Example 6: Using enumerate function
result = [value for _, value in enumerate(mylist) if value!= ""]

# Example 7: Using for loop
result = []
for item in mylist:
    if item != "":
        result.append(item)

# Example 8: Using len() method
for i in mylist:
    if(len(i)==0):
        mylist.remove(i)

# Example 9: Using join() + split() method
result = "".join(mylist).split()

# Example 10: Using lambda function
result = list(filter(lambda x: len(x) > 0, mylist))

# Example 11: Using functools.reduce()
result = functools.reduce(lambda a, b: a+[b] if b else a, mylist, [])

# Example 12: Using itertools.filterfalse()
result = list(itertools.filterfalse(lambda x: x == '', mylist))

# Example 13: Using filter() with custom function
def filter_empty_strings(value):
    return value != ""
result = list(filter(filter_empty_strings, mylist))

2. Remove an Empty String from the List Using the remove() Method

You can remove empty strings from a list using the remove() method in Python. First, create a list of strings and use the while loop to check if there are still empty strings("") present in the list("" in mylist). If an empty string is found, the remove() method will remove it from the list. The loop continues until all empty strings have been removed. Finally, the resulting list with no empty strings is printed.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Removing empty strings from list 
# Using remove() method
while("" in mylist):
    mylist.remove("")
print("After removing empty strings from the list: ", mylist)

Yields below output.

python remove empty strings list

3. Remove Empty Strings from the List Using filter() Method

To remove empty strings from a list use the filter() method. In this case, instead of using a lambda function as the filter criteria, you can pass None as the first argument to the filter() function.

In the below example, the filter(None, mylist) line filters the mylist list using None as the filter criteria. In Python, passing None as the filter function removes all the elements from the iterable (in this case, the list mylist) that are evaluated False in a boolean context. Since empty strings are evaluated False, they are removed from the list. Finally, the list() function is used to convert the filtered result back into a list.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using filter() Method
result = list(filter(None, mylist))
print("After removing empty strings from the list:", result)

Yields the same output as above.

4. Using filter() and Lambda Function

Similarly, you can use filter() method along with lambda to remove empty strings from a list. First, you can define a lambda function as the filter criteria and pass it along with the list to the filter() function.

In the below example, the lambda function lambda x:x!="" checks if each element x in the list is not an empty string. If the condition is true, the element is included in the filtered list. Finally, the list() function is used to convert the filtered result back into a list.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using filter() and lambda function
# to remove empty strings from list
result = list(filter(lambda x: x != "", mylist))
print("After removing empty strings from the list:", result)

Yields the same output as above.

5. Removing Empty Strings using List Comprehension

To remove empty strings from a list using list comprehension in Python. For example, the list comprehension [x for x in mylist if x!=””] creates a new list by iterating over each element x in the original list (mylist) and only include it in the new list if it is not an empty string (x != ""). This effectively removes all empty strings from the list. Finally, the new list is assigned back to the variable mylist.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Removing empty strings from list 
# Using list comprehension
result = [x for x in mylist if x != ""]
print("After removing empty strings from the list:",result)

# Using list comprehension
result = [i for i in mylist if i]
print("After removing empty strings from the list:",result)

Yields the same output as above.

6. Using enumerate() Function

To remove empty strings from a list using the enumerate() function, you can iterate over the enumerated list and filter out the empty strings. For example, the enumerate() function is used to iterate over the mylist list and provide both the index and value of each element. The list comprehension [value for,value in enumerate(mylist) if value != ""] iterates over each enumerated element, but only includes the value in the new list if it is not an empty string (value != ""). The is used as a placeholder for the index, which is not used in this case.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using enumerate function
result = [value for _, value in enumerate(mylist) if value!= ""]
print("After removing empty strings from the list:",result)

Yields the same output as above.

7. Remove Empty Strings from the List Using For Loop

To remove empty strings from a list of strings using a for loop, For example, first, you can initialize an empty list as a result. Then, you can iterate over each element item in the mylist using a for loop. For each item, you can check if it is not an empty string(item != ""). If it is not empty, you can append it to the result list.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using for loop
result = []
for item in mylist:
    if item != "":
        result.append(item)
print("After removing empty strings from the list:",result)

Yields the same output as above.

8. Remove Empty Strings from the List Using len() Method

To remove empty strings from a list using the len() method, you can iterate over the list and filter out the elements with a length of 0.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using len() method
for i in mylist:
    if(len(i)==0):
        mylist.remove(i)
print("After removing empty strings from the list:",mylist)

Yields the same output as above.

9. Remove Empty Strings Using join() + split() Method

You can also use the join() and split() methods in Python to remove empty strings from a list. By concatenating the list elements into a single string using join() and then splitting it using split(), you can obtain a list without empty strings.

For example, "".join(mylist) concatenates the list elements into a single string with no delimiter. The resulting string is "Welcome to SparkByExamples.com". Then, the split() method is called on this string without any arguments. It splits the string at whitespace characters and returns a list of non-empty substrings. This effectively removes the empty strings from the list.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using join() + split() method
result = "".join(mylist).split()
print("After removing empty strings from the list:",result)

Yields the same output as above.

10. Using Lambda Function

To remove empty strings from a list using a lambda function and the filter() function in Python. By checking the length of each element in the list using len(x)>0 as the lambda function, you can filter out the empty strings.

In the below example, the lambda function lambda x:len(x)>0 is used as the filter criteria in the filter() function. It checks if the length of each element x in the list is greater than 0. If the condition is true, the element is included in the filtered result. Finally, the list() function is used to convert the filtered result back into a list.


# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using lambda function
result = list(filter(lambda x: len(x) > 0, mylist))
print("After removing empty strings from the list:",result)

Yields the same output as above.

11. Using functools.reduce()

You can remove empty strings from a list using functools.reduce() and the lambda function correctly removes empty strings from the list and accumulates non-empty strings into a new list.


import functools

# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using functools.reduce()
result = functools.reduce(lambda a, b: a+[b] if b else a, mylist, [])
print("After removing empty strings from the list:",result)

Yields the same output as above.

12. Using itertools.filterfalse()

You can remove empty strings from a list using itertools.filterfalse() from the itertools module and a lambda function as the filter criteria. In this program, itertools.filterfalse() is used with the lambda function lambda x:x=='' as the filter criteria. The lambda function checks if each element x in the list is equal to an empty string. filterfalse() returns an iterator containing the elements for which the lambda function evaluates to False. Finally, list() is used to convert the iterator to a list.


import itertools

# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com",""]
print("Original List: ",mylist)

# Using itertools.filterfalse()
result = list(itertools.filterfalse(lambda x: x == '', mylist))
print("After removing empty strings from list:",result)

Yields the same output as above.

13. Using Filter with Custom Function

You can also use the filter() function along with a custom function that defines the filtering condition to remove empty strings from a list. For example, the filter_empty_strings() function defines the condition to filter out empty strings. It checks if the value is not equal to an empty string (""). The filter() function is then used with the filter_empty_strings function and the list mylist. It returns an iterator containing the elements for which the custom function evaluates to True. Finally, list() is used to convert the iterator to a list.


# Custom function to filter out empty strings
def filter_empty_strings(value):
    return value != ""

# Consider the list of strings
mylist = ["", "Welcome", "", "to", "", "SparkByExamples.com", ""]
print("Original List: ", mylist)

# Using filter() with custom function
result = list(filter(filter_empty_strings, mylist))
print("After removing empty strings from list:", result)

Yields the same output as above.

Conclusion

In this article, I have explained how to remove empty strings from the list by using multiple methods of Python such as the remove(), filter(), lambda, list comprehension,enumerate(), for loop, len(), join() + split(), functools.reduce(), itertools.filterfalse(), and filter() with custom functions with examples.

Happy Learning !!