Python – Remove empty strings from list of strings
When working with lists of strings in Python, you may encounter empty strings (” “) that need to be removed. We’ll explore various methods to Remove empty strings from a list.
Using List Comprehension
List comprehension is the most concise and efficient method to filter out empty strings. This method is ideal for most scenarios due to its simplicity and efficiency.
a = ["Geeks", "", "for", " ", "Geeks", ""]
# Remove empty strings
a = [x for x in a if x.strip()]
print(a)
Output
['Geeks', 'for', 'Geeks']
Explanation:
- The
strip()
method removes leading and trailing whitespaces. - The condition
if
x.strip()
checks for non-empty strings after removing whitespaces. - The filtered list contains only valid strings.
Let’s explore some more methods to remove empty strings from list of strings
Table of Content
Using filter()
filter()
function works well when combined with a lambda function. Use this method for functional programming scenarios.
a = ["Geeks", "", "for", " ", "Geeks", ""]
# Remove empty strings
a = list(filter(lambda x: x.strip(), a))
print(a)
Output
['Geeks', 'for', 'Geeks']
Explanation:
lambda
x: x.strip()
function checks if a string is non-empty after stripping whitespaces.filter()
filters out the strings that do not meet the condition.
Using remove()
remove()
method can be used in a loop to delete empty strings iteratively. This method is useful when modifying the original list directly.
a = ["Geeks", "", "for", " ", "Geeks", ""]
# Remove empty strings
for x in a[:]:
if not x.strip():
a.remove(x)
print(a)
Output
['Geeks', 'for', 'Geeks']
Explanation:
- Iterates over a copy of the list (
a[:]
) to avoid modification issues. not
x.strip()
identifies empty strings to be removed.
Using filter() with None
filter()
function can directly filter out falsy values like empty strings when used with None
.
a = ["Geeks", "", "for", " ", "Geeks", ""]
# Remove empty strings
a = list(filter(None, map(str.strip, a)))
print(a)
Output
['Python', 'is', 'fun!']
Explanation:
map(str.strip, a)
removes leading and trailing whitespaces from all strings.filter(None, ...)
removes all falsy values (e.g., empty strings,None
).