Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove empty string in a list?

Tags:

For example I have a sentence

"He is so .... cool!" 

Then I remove all the punctuation and make it in a list.

["He", "is", "so", "", "cool"] 

How do I remove or ignore the empty string?

like image 780
Alexa Elis Avatar asked Apr 19 '13 07:04

Alexa Elis


People also ask

How do I remove blank strings from a list?

Method #1: Using remove() This particular method is quite naive and not recommended use, but is indeed a method to perform this task. remove() generally removes the first occurrence of an empty string and we keep iterating this process until no empty string is found in list.

How do I remove an empty value from a list?

The easiest way is list comprehension to remove empty elements from a list in Python. And another way is to use the filter() method. The empty string "" contains no characters and empty elements could be None or [ ], etc.

How do I remove a string from a list in Python?

Method #1 : Using remove() remove() generally removes the first occurrence of K string and we keep iterating this process until no K string is found in list.

How do you remove blank rows from a list in Python?

Short answer: You can remove all empty lists from a list of lists by using the list comprehension statement [x for x in list if x] to filter the list.


2 Answers

You can use filter, with None as the key function, which filters out all elements which are Falseish (including empty strings)

>>> lst = ["He", "is", "so", "", "cool"] >>> filter(None, lst) ['He', 'is', 'so', 'cool'] 

Note however, that filter returns a list in Python 2, but a generator in Python 3. You will need to convert it into a list in Python 3, or use the list comprehension solution.

Falseish values include:

False None 0 '' [] () # and all other empty containers 
like image 96
Volatility Avatar answered Sep 17 '22 18:09

Volatility


You can filter it like this

orig = ["He", "is", "so", "", "cool"] result = [x for x in orig if x] 

Or you can use filter. In python 3 filter returns a generator, thus list() turns it into a list. This works also in python 2.7

result = list(filter(None, orig)) 
like image 22
msvalkon Avatar answered Sep 18 '22 18:09

msvalkon