How do I remove empty strings from a list in Python?

I’m modifying a Python program that generates a list of strings and for some reason some of the strings in the list are empty. How can I remove empty strings from the list to avoid errors in my program?

Method 1: Basic Loop Iteration

In this method, we use a simple for loop to iterate through each element in the original_list. We then check if each element is not an empty string (“”). If it’s not empty, we add it to the cleaned_list.

Finally, we print both the original and cleaned lists.

# Define the original list
original_list = ["apple", "", "banana", "", "cherry", ""]

# Initialize an empty list to store non-empty items
cleaned_list = []

# Iterate through each item in the original list
for item in original_list:
    # Check if the item is not an empty string
    if item != "":
        # If not empty, append it to the cleaned list
        cleaned_list.append(item)


# Print the original and cleaned lists
print("Original List:", original_list)
print("Cleaned List:", cleaned_list)

The output of this code is:

Original List: ['apple', '', 'banana', '', 'cherry', '']
Cleaned List: ['apple', 'banana', 'cherry']

Explanation

  • Original List: [‘apple’, ”, ‘banana’, ”, ‘cherry’, ”]: This is the list with some elements being empty strings.
  • Loop Iteration: The for item in original_list: loop iterates through each element in original_list.
  • Conditional Check: The if item != “”: statement checks if the current item is not an empty string.
  • Appending to Cleaned List: If the item is not empty, it is appended to the cleaned_list using cleaned_list.append(item).
  • Print Statements: The print statements at the end display both the original and cleaned lists.

Advantages and Considerations

  • Simplicity: This method is easy to understand, making it a good choice for beginners.
  • Readability: The logic is explicit and follows a natural flow, making it easy to follow the code’s purpose.
  • Verbose: However, it may seem a bit verbose, especially compared to more advanced techniques like list comprehensions.

Method 2: Using List Comprehension

The list comprehension is a concise and powerful feature in Python that allows you to create lists with a single line of code.

In this section, you will use a list comprehension to iterate through each element in original_list and only include elements that are not empty strings in the cleaned_list.

# Define the original list
original_list = ["apple", "", "banana", "", "cherry", ""]

# Use list comprehension to create cleaned_list
cleaned_list = [item for item in original_list if item != ""]

# Print the original and cleaned lists
print("Original List:", original_list)
print("Cleaned List:", cleaned_list)

The output of the Python code above is:

Original List: ['apple', '', 'banana', '', 'cherry', '']
Cleaned List: ['apple', 'banana', 'cherry']

Explanation

  • Original List: [‘apple’, ”, ‘banana’, ”, ‘cherry’, ”]: This is the list that contains some empty strings.
  • List Comprehension: The line cleaned_list = [item for item in original_list if item != “”] is a list comprehension. It creates a new list (cleaned_list) by iterating through each item in original_list and including only those items that are not empty strings.
  • Print Statements: The print statements at the end display both the original and cleaned lists.

Advantages and Considerations

  • Conciseness: List comprehensions allow you to express the same logic in a more compact form, reducing the number of lines of code.
  • Readability: While it might seem more concise, it’s important to note that readability is subjective. For those familiar with list comprehensions, the code is often considered more Pythonic.
  • Efficiency: List comprehensions are often more efficient than traditional loops and can be a performance improvement in certain scenarios.
  • Pythonic: The use of list comprehensions aligns with the Pythonic philosophy of writing code that is clear, expressive, and idiomatic for the language.

Method 3: Filtering with filter() Function

With this method, you utilize Python’s built-in filter() function, which provides a concise way to apply a function to each element in an iterable and return only the elements that satisfy a given condition.

In this case, you will use a lambda function to filter out empty strings from original_list.

# Define the original list
original_list = ["apple", "", "banana", "", "cherry", ""]

# Use filter() function with a lambda function
cleaned_list = list(filter(lambda x: x != "", original_list))

# Print the original and cleaned lists
print("Original List:", original_list)
print("Cleaned List:", cleaned_list)

Execute this code on your computer, you will see the following output:

Original List: ['apple', '', 'banana', '', 'cherry', '']
Cleaned List: ['apple', 'banana', 'cherry']

Explanation

  • Original List: [‘apple’, ”, ‘banana’, ”, ‘cherry’, ”]: This is the list with some elements being empty strings.
  • Filter Function: The line cleaned_list = list(filter(lambda x: x != “”, original_list)) utilizes the filter() function. The filter() function takes two arguments: a function and an iterable. In this case, the function is a lambda function that checks if an element is not an empty string (x != “”). The filter() function then returns an iterator containing only the elements from original_list that satisfy the condition.
  • Conversion to List: The list() function converts the iterator returned by filter() into a list.
  • Print Statements: The print statements at the end display both the original and cleaned lists.

Advantages and Considerations

  • Conciseness: The filter() function, along with a lambda function, allows for a concise expression of the filtering condition.
  • Functional Programming: This approach aligns with functional programming principles by applying a function to each element in the iterable.
  • Versatility: The filter() function is versatile and can be used for more complex filtering conditions.
  • Lambda Functions: Understanding and using lambda functions is a key skill in Python programming.

Method 4: Using if Condition in List Comprehension

This method is an alternative to using a lambda function in a list comprehension. Instead, it uses the fact that empty strings evaluate to False in a boolean context.

By using the if item condition in the list comprehension, you include only those elements in cleaned_list that are truthy (i.e. not empty strings).

# Define the original list
original_list = ["apple", "", "banana", "", "cherry", ""]

# Use if condition in list comprehension
cleaned_list = [item for item in original_list if item]

# Print the original and cleaned lists
print("Original List:", original_list)
print("Cleaned List:", cleaned_list)

Let’s confirm that the output is correct:

Original List: ['apple', '', 'banana', '', 'cherry', '']
Cleaned List: ['apple', 'banana', 'cherry']

Yes, the output is correct!

Explanation

  • Original List: [‘apple’, ”, ‘banana’, ”, ‘cherry’, ”]: This is the list that contains some empty strings.
  • List Comprehension: The line cleaned_list = [item for item in original_list if item] is a list comprehension. The if item condition filters out elements that evaluate to False in a boolean context. Since empty strings are considered falsy, they are excluded from the cleaned_list.
  • Print Statements: The print statements at the end display both the original and cleaned lists.

Advantages and Considerations

  • Conciseness: This method is concise and readable, making it an attractive alternative to a lambda function.
  • Boolean Evaluation: It leverages the truthy/falsy nature of elements in a boolean context, making the code more explicit.
  • Readability: For those who find lambda functions intimidating, this approach provides a straightforward and readable alternative.
  • Consistency with Pythonic Style: It aligns with Pythonic coding style by using the truthy/falsy evaluation.

Conclusion

In this tutorial, we have explored multiple ways to remove empty strings from a list in Python, ranging from basic loop iteration to more advanced techniques like list comprehensions, the filter() function, and lambdas.

Choosing the right method depends on your preference and the complexity of your code.

Leave a Comment