Q:

Remove empty strings from a list of strings using python programming

0

Remove empty strings from a list of strings

Given:

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]

Expected Output:

Original list of sting
['Emma', 'Jon', '', 'Kelly', None, 'Eric', '']

After removing empty strings
['Emma', 'Jon', 'Kelly', 'Eric']

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  • Use the built-in function filter() to remove empty strings from a list
  • Or use the for loop and if condition to remove the empty strings from a list

Solution1:Using the loop and if condition

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]
res_list = []
for s in str_list:
    # check for non empty string
    if s:
        res_list.append(s)
print(res_list)

Solution2:Using the built-in function filter()

str_list = ["Emma", "Jon", "", "Kelly", None, "Eric", ""]

# use built-in function filter to filter empty value
new_str_list = list(filter(None, str_list))

print("After removing empty strings")
print(new_str_list)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now