How to Remove Empty Strings from List in Python Easily
To remove empty strings from a list in Python, use a
list comprehension that filters out empty strings by checking if each string is truthy. For example, [s for s in my_list if s] creates a new list without empty strings.Syntax
The common syntax to remove empty strings from a list uses a list comprehension:
[s for s in my_list if s]: Creates a new list including only strings that are not empty.
Here, my_list is your original list, s is each element, and if s checks if the string is not empty (non-empty strings are "truthy" in Python).
python
[s for s in my_list if s]
Example
This example shows how to remove empty strings from a list of strings using a list comprehension.
python
my_list = ["apple", "", "banana", "", "cherry", ""] clean_list = [s for s in my_list if s] print(clean_list)
Output
['apple', 'banana', 'cherry']
Common Pitfalls
One common mistake is trying to remove empty strings by comparing with an empty string using == inside a loop without creating a new list, which does not modify the original list correctly.
Another pitfall is using remove() inside a loop, which can cause skipping elements or errors.
python
my_list = ["apple", "", "banana", "", "cherry", ""] # Wrong way: modifying list while iterating for s in my_list[:]: if s == "": my_list.remove(s) print(my_list) # Output is ['apple', 'banana', 'cherry'] # Right way: use list comprehension my_list = ["apple", "", "banana", "", "cherry", ""] clean_list = [s for s in my_list if s] print(clean_list)
Output
['apple', 'banana', 'cherry']
['apple', 'banana', 'cherry']
Quick Reference
Tips to remember when removing empty strings from lists:
- Use list comprehensions for clean and efficient filtering.
- Empty strings are "falsy" in Python, so
if sfilters them out. - Avoid modifying lists while iterating over them.
Key Takeaways
Use list comprehensions with
if s to remove empty strings efficiently.Empty strings are considered false in Python, so filtering with
if s works well.Avoid removing items from a list while looping over it to prevent unexpected behavior.
Creating a new filtered list is safer and clearer than modifying the original list in place.