w3resource

Python function to filter out empty strings from a list


5. Empty String Remover

Write a Python function that filters out all empty strings from a list of strings using the filter function.

Sample Solution:

Python Code:

def filter_non_empty_strings(strings):
    """
    Filters out all empty strings from a list of strings.

    Args:
        strings (list): A list of strings.

    Returns:
        list: A new list containing only non-empty strings.
    """
    # Define the filtering function
    def is_non_empty_string(s):
        return s.strip() != ""

    # Use the filter function to filter out empty strings
    non_empty_strings = list(filter(is_non_empty_string, strings))

    return non_empty_strings

# Example usage:
strings = ["", "w3resource", "Filter", "", "Python", ""]
print("Original list of strings:",strings)
print("\nA new list containing only non-empty strings:")
result = filter_non_empty_strings(strings)
print(result)  

Explanation:

In the exercise above -

  • First, the "filter_non_empty_strings()" function takes a list of strings called strings as input.
  • Inside the function, we define a nested function "is_non_empty_string()" that checks if a string is non-empty by using the strip() method to remove leading and trailing whitespace and then checking if it's an empty string.
  • We use the filter() function to filter out empty strings from the strings list by applying the "is_non_empty_string()" function as the filtering condition.
  • The filtered 'non_empty_strings' are converted to a list and returned as the result.

Sample Output:

Original list of strings: ['', 'w3resource', 'Filter', '', 'Python', '']

A new list containing only non-empty strings:
['w3resource', 'Filter', 'Python']

Flowchart:

Flowchart: Python function to filter out empty strings from a list.

For more Practice: Solve these Related Problems:

  • Write a Python program to filter out all empty strings and strings containing only whitespace from a list using the filter function.
  • Write a Python function that uses filter to remove strings that are either empty or contain only digits from a list.
  • Write a Python program to filter a list of strings to remove empty entries and then concatenate the remaining strings into a single sentence.
  • Write a Python program that filters out empty strings from a list and then trims extra whitespace from the remaining strings using the filter function.


Go to:


Previous: Python program to extract names starting with vowels.
Next: Python program to filter students by high grades.

Python Code Editor:

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.