Remove empty strings from a list of strings
my_list = ["hello", "", "world", "", "goodbye"]
my_list = [x for x in my_list if x != ""]
print(my_list)
Watch a video course
Python - The Practical Guide
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"]