list processing
string manipulation
python programming
data cleaning
coding tips

Remove empty strings from a list of strings

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

Removing empty strings from a list of strings is a common task in data processing and cleaning. This operation ensures that subsequent data analyses or operations are performed on meaningful data, improving both the performance and the accuracy of your programs.

Understanding the Problem

When processing strings from various data sources, it's common to encounter empty strings, represented by "" in Python. These empty strings can occur due to several reasons such as file parsing errors, omitted data, or even as placeholders. While they may not seem harmful, having extraneous empty strings in your dataset can distort analyses, skew results, and introduce errors.

Technical Approaches to Remove Empty Strings

There are multiple ways to remove empty strings from a list in Python, each with its trade-offs. We'll explore several methods below.

1. Using List Comprehension

List comprehension provides a concise way to filter elements from a list. This method inherently creates a new list containing only non-empty strings.

python
1# Original list with some empty strings
2strings = ["apple", "", "banana", "", "cherry", ""]
3
4# Remove empty strings using list comprehension
5filtered_list = [string for string in strings if string]
6
7print(filtered_list)  # Output: ['apple', 'banana', 'cherry']

2. Using the filter() Function

The filter() function is a built-in Python method used to return an iterator from a given iterable (e.g., list, string) by filtering out elements that do not satisfy a function (returns False).

python
1# Using filter() to remove empty strings
2filtered_iterator = filter(None, strings)
3
4# Convert the iterator to a list
5filtered_list = list(filtered_iterator)
6
7print(filtered_list)  # Output: ['apple', 'banana', 'cherry']

3. Using a for Loop

While less elegant than the previous methods, a for loop is straightforward and easy to understand, which can be beneficial for learners and beginners.

python
1# Using a for loop to remove empty strings
2filtered_list = []
3for string in strings:
4    if string:  # Checks for non-empty string
5        filtered_list.append(string)
6
7print(filtered_list)  # Output: ['apple', 'banana', 'cherry']

Performance Considerations

Choosing the best method depends on the context in which you are working. Generally, list comprehension is favored for its balance of readability and performance. The filter() function works similarly, though older Python versions might require additional consideration for handling iterators.

Performance Comparison Table

MethodComplexityDescription
List ComprehensionO(n)Concise and efficient for most cases.
filter() FunctionO(n)Clean, uses iterators which may be more efficient in certain cases.
for LoopO(n)Simple and explicit; potentially less efficient for large datasets.

Additional Considerations

Edge Cases

When removing empty strings, consider what qualifies as an "empty" string. Typically, "" is considered empty, but other whitespace-only strings (e.g., " ", "\n") may also need to be stripped or removed based on the context of your data.

python
1# Remove strings that are entirely whitespace
2strings_with_whitespace = ["apple", " ", "banana", "\n", "cherry", ""]
3
4# Using list comprehension to remove both empty and whitespace-only strings
5filtered_list = [string for string in strings_with_whitespace if string.strip()]
6
7print(filtered_list)  # Output: ['apple', 'banana', 'cherry']

Non-Python Implementations

While this article focuses on Python, the concept of removing empty strings applies across programming languages. For instance, in JavaScript, this could be achieved by using Array.prototype.filter() and similar conditional checks:

javascript
let strings = ["apple", "", "banana", "", "cherry", ""];
let filteredList = strings.filter(string => string !== "");
console.log(filteredList);  // Output: ['apple', 'banana', 'cherry']

Conclusion

Removing empty strings from a list is an essential step in cleaning up data for effective processing and analysis. Python offers several efficient methods to perform this task, balancing ease of use with computational efficiency. Being aware of any special types of "empty" or "insignificant" data, such as whitespace-only strings, enhances the robustness of your data cleaning process, ensuring cleaner, more accurate datasets.


Related reading
Course
Intermediate
27 lessons
15 hours
DSA Fundamentals

Master algorithmic patterns and data structures through hands-on LeetCode-style problems - from arrays and hashing to dynamic programming and advanced graphs.

View the course
Track what you have practised

A free account saves your progress, solutions and study plan across every problem on Codemia.

Data Structures & Algorithms practice on Codemia

Step through 300 algorithm problems with animated visualisers that show the data structure changing as the code runs.

Practice algorithms

All Rights Reserved.