Remove Empty Strings from a List of Strings

Remove empty strings from a list of strings

I would use filter:

str_list = filter(None, str_list)
str_list = filter(bool, str_list)
str_list = filter(len, str_list)
str_list = filter(lambda item: item, str_list)

Python 3 returns an iterator from filter, so should be wrapped in a call to list()

str_list = list(filter(None, str_list))

Removing empty strings in a list

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

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

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

How to remove an empty string from a list in python?

I guess you should not remove while iterating through the list.
Try

b = list(filter(None, b))

or

b = [s for s in b if not b == '']

or

for i in range( len(b) - 1, -1, -1) :
if i == '':
b.del(i)

The first and second are more functional solutions,

and the third iterates through the list in reverse.

Remove empty entries from list of list of strings

Why not use the List<T>.RemoveAll() method? Definition:

Removes all the elements that match the conditions defined by the specified predicate.

foreach (var l in list)
{
l.RemoveAll(x => string.IsNullOrEmpty(x));
}

That is all you need. Other answer have Select().Where() and twice ToList(), which is way too much overhead for a simple action like this.

Remove empty string from a list of strings

The list comprehension isn't quite right, for df['name'] in df doesn't make sense. Try with:

df['name'] = [[s for s in l if s] for l in df['name']]

df = pd.DataFrame({'name':[['anna','karen','',], ['', 'peter','mark','john']]})

df['name'] = [[s for s in l if s] for l in df['name']]
print(df)
name
0 [anna, karen]
1 [peter, mark, john]

How to remove empty string in a list?

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

Remove empty string in list in Julia

new_li = filter((i) -> i != " ", li)

or

new_li = [i for i in li if i != " "]

Removing empty string from a list

Try

mylist = [x for x in mylist if x!= '']

Remove empty strings in a list of lists in R

you can use lapply and simple subsetting:

x <- list(c("", "alteryx", "confirme", "", "", "", "ans", "", ""))
lapply(x, function(z){ z[!is.na(z) & z != ""]})

[[1]]
[1] "alteryx" "confirme" "ans"

lapply applies a function to every component of a list. In this case the function is a simple subsetting function.



Related Topics



Leave a reply



Submit