0

I have a list in the form

lst = ['', 'how', '', 'are', 'you', '']

and want to convert it into

lst = ['how','are', 'you']

I have currently used the code list(filter(None,lst)) but no changes are returned. How can i remove the empty strings?

2
  • 1
    list(filter(None,lst)) works for me. Commented Apr 27, 2021 at 14:06
  • 1
    filter is not something that works "in place" you need to assign that back to lst Commented Apr 27, 2021 at 14:14

4 Answers 4

3

Your code must works but an other solution is using lambdas:

lst = list(filter(lambda x: x != '', lst))
print(lst)

Output: ['how', 'are', 'you']

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks @dgrana. My list had white spaces within the empty strings. I ddnt write it well on the question. lst = [' ', 'how', ' ', 'are', 'you', ' ' ]. Your solution works well. Thanks
2

Here you forgot to make the filter to this kinda thing:

lst = ['', 'how', '', 'are', 'you', '']
lst = list(filter(None, lst))
print(lst)

you define the list as list(filter(None, lst))

Comments

2

A simple and possible solution is the following:

lst = ['', 'how', '', 'are', 'you', '']

lst = [element for element in lst if element != '']

Now, lst is ['how', 'are', 'you']

2 Comments

I love comprehensions. You might think about dropping the != "" as it is not technically needed.
@JonSG it's helpful to mention why it's not technically needed, because it's not immediately obvious if you don't already know it -- because empty strings are falsy in python
1

Are you printing lst again? Your code works for me.

lst = ['', 'how', '', 'are', 'you', '']
lst = list(filter(None,lst))
print(lst)

outputs ['how', 'are', 'you']

1 Comment

thanks for your replies. Actually my list is lst = [' ', 'how', ' ', 'are', 'you', ' ' ]. Notice the empty strings have a white space in between, and not as how i wrote in previously. filter function won't remove them. Should I assume that [' '] is not actually an empty string ?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.