W3docs

Remove empty strings from a list of strings

This code uses a list comprehension to iterate through the original list and only keep the elements that are not empty strings.

Remove empty strings from a list of strings using a list comprehension

my_list = ["hello", "", "world", "", "goodbye"]
my_list = [x for x in my_list if x != ""]
print(my_list)

<div class="alert alert-info flex not-prose"> Watch a course <span class="hidden md:block">Watch a video course </span> Python - The Practical Guide</div>

This code uses a list comprehension to iterate through the original list and only keep the elements that are not empty strings. The resulting list is then assigned back to the variable my_list and will contain only the non-empty strings. The final line prints the modified list.


# Output: ["hello", "world", "goodbye"]