Remove empty elements from a list in Python

In this tutorial we will learn how to use the empty elements from a list and  Python, lists are a versatile data structure that can hold elements of any data type, including other lists. Sometimes, lists may contain empty elements (e.g., empty strings '', None, 0, [], etc.) that you want to remove for various reasons, such as data cleaning or processing efficiency.

Using list comprehension:

List comprehension offers a concise and Pythonic way to create lists. In this method, a new list is constructed by iterating over the original list and only including elements that evaluate to True (i.e., not empty). The syntax [elem for elem in my_list if elem] creates a new list by iterating over each element elem in my_list and only including elem if it’s truthy

my_list = [elem for elem in my_list if elem]

Using filter() function:

  • The filter() function applies a function to each element of the iterable (in this case, the list) and returns an iterator yielding those items for which the function returns True. Passing None as the function argument effectively filters out elements that evaluate to False. Using list() to convert the resulting iterator back into a list gives you the list without empty elements.
  • my_list = list(filter(None, my_list))

    Using a loop:

  • This method uses a for loop to iterate over each element in the list. If the element evaluates to True, it’s appended to a new list. After iterating through all elements, the original list is updated to contain only the non-empty elements.
    new_list = []
    for elem in my_list:
        if elem:
            new_list.append(elem)
    my_list = new_list

    output :

  • [‘apple’, ‘banana’, ‘orange’]
  • These methods offer flexibility and performance advantages depending on the specific requirements and context of your program. List comprehension is often preferred for its readability and succinctness, while using filter() might be preferred for functional programming style. Looping offers more control and is suitable for more complex filtering conditions.

Leave a Comment

Your email address will not be published. Required fields are marked *

Scroll to Top