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 returnsTrue. PassingNoneas the function argument effectively filters out elements that evaluate toFalse. Usinglist()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
forloop to iterate over each element in the list. If the element evaluates toTrue, 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_listoutput :
- [‘apple’, ‘banana’, ‘orange’]
-