emmasa
emmasa

Reputation: 207

Removing empty strings in a list

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?

Upvotes: 0

Views: 615

Answers (4)

will-hedges
will-hedges

Reputation: 1284

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']

Upvotes: 1

dgrana
dgrana

Reputation: 108

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

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

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

Upvotes: 3

agus.dinamarca
agus.dinamarca

Reputation: 99

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']

Upvotes: 2

lll
lll

Reputation: 122

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))

Upvotes: 2

Related Questions