Python remove empty elements from list | Example code

The easiest way is list comprehension to remove empty elements from a list in Python. And another way is to use the filter() method. The empty string "" contains no characters and empty elements could be None or [ ], etc.

Python remove empty elements from a list Example

Simple examples code.

Using list comprehension

Simp;e iterate through the list and add the non-empty elements.

list1 = ['A', '   ', ' ', 'B', '            ', 'C']
res = [ele for ele in list1 if ele.strip()]
print(res)

list2 = [1, 6, [], 3, [], [], 9]
res = [ele for ele in list2 if ele != []]
print(res)

Output:

Python remove empty elements from list

Using filter() method

Just filter out the None and empty element form list.

If None is used as the first argument to filter(), it filters out every value in the given list, which is False in a boolean context. This includes empty lists.

list2 = [1, 6, [], 3, [], [], 9]

res = list(filter(None, list2))
print(res)

Output: [1, 6, 3, 9]

Use a for loop to remove empty strings from a list

Iterate through the list and check if each string is not an empty string. If it is not an empty string, then add each non-empty string to an initially empty list using the append method.

list1 = ['A', '   ', ' ', 'B', '            ', 'C']

res = []
for i in list1:
    if i.strip() != '':
        res.append(i)
print(res)


list2 = [1, 6, [], 3, [], [], 9]
res = []
for i in list2:
    if i:
        res.append(i)
print(res)

Output:

[‘A’, ‘B’, ‘C’]
[1, 6, 3, 9]

If you want to get rid of everything that is “falsy”, e.g. empty strings, empty tuples, zeros, you could also use

list2 = [x for x in list1 if x]

Do comment if you have any doubts and suggestions on this Python List topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.