Remove blank strings from a Python List

This tutorial will discuss multiple ways to remove blank strings from a Python list.

Table Of Contents

Method 1: Using List Comprehension

To remove all the blank strings from a Python list, you can iterate over the list using list comprehension and skip the empty strings. This will return a new list that does not contain any empty strings.

This is the quickest and easiest solution.

Let’s see the complete example,

# List of strings
sampleList = ["testing", "", "java", "python", ""]
print("Original List:", sampleList)

# Remove blank strings from List
sampleList =  [item for item in sampleList if item]

print("List after removing blank strings:")
print(sampleList)

Output

Original List: ['testing', '', 'java', 'python', '']
List after removing blank strings:
['testing', 'java', 'python']

Method 2: Using filter() Method

Another approach is to use the filter() method. You can call the filter() method, passing None as the first argument and the list as the second argument. This will filter out all the strings from the list that evaluate to False, for example, empty strings. As a result, it will exclude all empty strings from the list and return a filtered object.

You can then convert this object back to a list to get a new list without any blank strings.

Let’s see the complete example,

# List of strings
sampleList = ["testing", "", "java", "python", ""]
print("Original List:", sampleList)

# Remove blank strings from List
sampleList =  list(filter(None, sampleList))

print("List after removing blank strings:")
print(sampleList)

Output

Original List: ['testing', '', 'java', 'python', '']
List after removing blank strings:
['testing', 'java', 'python']

Summary

Today, we learned about remove blank strings from a Python list.

Leave a Comment

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

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Scroll to Top