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:
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.3.3 (Community Edition)
Windows 10
Python 3.10.1
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.