How to Remove Empty Strings from a List of Strings in Python?

Estimated read time 1 min read

You can remove empty strings from a list of strings using a list comprehension with a filter condition that checks if the string is empty or not. Here’s an example:

list_of_strings = ['', 'hello', '', 'world', '']
new_list_of_strings = [s for s in list_of_strings if s]
print(new_list_of_strings) # Output: ['hello', 'world']

In this example, we have a list of strings (list_of_strings). We want to create a new list (new_list_of_strings) that only contains strings that are not empty. We achieve this by using list comprehension with a filter condition if s, which checks if the string s is not empty. The resulting list contains only the non-empty strings.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply