How to Remove Empty Strings from a List in Python — CODEFATHER

Claudio Sabato
6 min readDec 1, 2023

When working with data in Python, lists are a versatile and commonly used data structure. However, it’s not uncommon to encounter lists that contain empty strings, which can be a hurdle in data processing.

In this guide, we will explore various methods to remove empty strings from Python lists.

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…

--

--

Claudio Sabato

Claudio Sabato is an IT expert with over 15 years of professional experience in Python/Bash programming, Linux Systems Administration and IT Systems Design.