0

I want to remove empty strings from a list:

['""', 'live', '""', '""']

Using code:

list = [ele for ele in list if ele.strip()]
        print(list)

Output:

['""', 'live', '""', '""']

Wanted result:

['live']
2
  • 1
    The input strings aren't empty. They have double quote characters in them. If you want to remove these, you will need to adjust the if condition to check for strings with double quotes, too. Commented Jul 18, 2022 at 6:25
  • @Code-Apprentice Amazing! Thank you for letting me notate that. I appreciate that. Commented Jul 18, 2022 at 6:30

3 Answers 3

3

This is not empty string, it is '""', try this:

lst = ['""', 'live', '""', '""']
res = [ele for ele in lst if ele != '""']
print(res)

Update Check and remove empty string too -> ('')

lst = ['""', 'live', '""', '""', '', '']
res = [ele for ele in lst if not ele in ['""', '']]
print(res)

['live']
Sign up to request clarification or add additional context in comments.

Comments

2

None of the strings in your list are empty. Try this as input instead:

['', 'live', '']

Your code will give the correct output in this case.

If you also want to remove strings such as '""', you will have to adjust the if condition to do so.

1 Comment

Thank you! I appreciate your effort Sir.
0

As Code-Apprentice mentioned, they are not empty values in your list but you can filter the list as follows:

sample_list = ['""', 'live', '""', '""']
sample_list = list(filter(('""').__ne__, sample_list))

1 Comment

('""').__ne__ is very... iffy, even though it might be tempting to not use a lambda. Still, maybe lambda e: e != '""' ? However, neither will remove actual empty strings...