Python Filter Empty Strings from a List

5/5 - (1 vote)

Below, we explore several methods to filter out empty strings from a list in Python.

πŸ’‘ Problem Formulation: Given a list of strings like my_list = ["apple", "", "banana", "cherry", ""], we want to produce a new list that contains only the non-empty strings: ["apple", "banana", "cherry"].

Method 1: Using a for-loop

The most straightforward approach to filter out empty strings from a list is by iterating over the list with a for-loop and appending non-empty strings to a new list.

Code Example:

my_list = ["apple", "", "banana", "cherry", ""]
filtered_list = []
for string in my_list:
    if string:
        filtered_list.append(string)

This loop checks each element in my_list. If the element is a non-empty string, it’s added to filtered_list. The condition if string evaluates to False for empty strings, thus they are not added.

Method 2: List Comprehension

List comprehension allows for more concise code for the same task as a for-loop. It is a more Pythonic way to create a new list by filtering the existing one.

Code Example:

my_list = ["apple", "", "banana", "cherry", ""]
filtered_list = [string for string in my_list if string]

This is a more compact version of Method 1. It accomplishes the filtering in a single line of code by iterating through each element and including it in the new list only if it evaluates to True, that is if it’s not an empty string.

Check out my new Python book Python One-Liners (Amazon Link).

If you like one-liners, you’ll LOVE the book. It’ll teach you everything there is to know about a single line of Python code. But it’s also an introduction to computer science, data science, machine learning, and algorithms. The universe in a single line of Python!

The book was released in 2020 with the world-class programming book publisher NoStarch Press (San Francisco).

Publisher Link: https://nostarch.com/pythononeliners

Method 3: Using filter() Function

The built-in filter() function is another tool to create an iterator that contains only items for which a function returns True. In this case, the function is the built-in bool() which returns False for empty strings.

Code Example:

my_list = ["apple", "", "banana", "cherry", ""]
filtered_list = list(filter(bool, my_list))

filter() takes two arguments: a function and an iterable. Here, it applies bool to each element. Since bool('') is False, empty strings are omitted. The result is converted back to a list.

Method 4: Using filter() with a Lambda Function

Instead of using bool, we can specify our own function with a lambda to accomplish the same task.

Code Example:

my_list = ["apple", "", "banana", "cherry", ""]
filtered_list = list(filter(lambda x: x != "", my_list))

Here, the lambda function lambda x: x != "" explicitly checks if the string is not empty. filter() creates an iterator only with the non-empty strings, which we then convert to a list.

Method 5: List Comprehension with len()

This method explicitly uses the len() function within a list comprehension to check for non-empty strings based on their length.

Code Example:

my_list = ["apple", "", "banana", "cherry", ""]
filtered_list = [string for string in my_list if len(string) > 0]

Instead of relying on the truthiness of a string, this list comprehension checks if the length of each string is greater than zero. If so, the string is included in the new list.

Bonus One-Liner Method 6: Using filter() and None

An even more succinct version of the filter() method is to pass None as the function, which automatically removes all falsey values.

Code Example:

my_list = ["apple", "", "banana", "cherry", ""]
filtered_list = list(filter(None, my_list))

When None is passed as the first argument to filter(), it filters out all items that are evaluated to False in a boolean context, which includes empty strings, resulting in the desired list.

Summary/Discussion

Each method shown above provides a different way to remove empty strings from a list in Python, ranging from the straightforward for-loop to more concise expressions using list comprehensions and the filter() function.

While they all achieve the same end result, list comprehensions and filter() tend to be more idiomatic and concise, aligning well with Python’s philosophy of code readability and simplicity.

If you want to learn more about writing clean code, check out my book: πŸ‘‡


The Art of Clean Code

Most software developers waste thousands of hours working with overly complex code. The eight core principles in The Art of Clean Coding will teach you how to write clear, maintainable code without compromising functionality. The book’s guiding principle is simplicity: reduce and simplify, then reinvest energy in the important parts to save you countless hours and ease the often onerous task of code maintenance.

  1. Concentrate on the important stuff with the 80/20 principle — focus on the 20% of your code that matters most
  2. Avoid coding in isolation: create a minimum viable product to get early feedback
  3. Write code cleanly and simply to eliminate clutter 
  4. Avoid premature optimization that risks over-complicating code 
  5. Balance your goals, capacity, and feedback to achieve the productive state of Flow
  6. Apply the Do One Thing Well philosophy to vastly improve functionality
  7. Design efficient user interfaces with the Less is More principle
  8. Tie your new skills together into one unifying principle: Focus

The Python-based The Art of Clean Coding is suitable for programmers at any level, with ideas presented in a language-agnostic manner.