Kumar Tanmay
Kumar Tanmay

Reputation: 183

How do I remove ' ' from a list?

I am trying to remove ' ' from the list and it gives me IndexError: list out of range

I have tried new_string.remove(' ') as well

def func_name(new_string):
   for k in range(len(new_string)):
       if new_string[k] == '':
           new_string = new_string[:k] + new_string[k+1:]
   return new_string

print func_name(['Title','','This','is','a','link','.'])

print func_name(['','','Hello','World!','',''])

print func_name(['',''])

Upvotes: 0

Views: 95

Answers (3)

vvvvv
vvvvv

Reputation: 31800

You should try a more pythonic way, like this:

def func_name(new_string):
    return [s for s in new_string if s != '']

print func_name(['Title', '', 'This', 'is', 'a', 'link', '.'])

print func_name(['', '', 'Hello', 'World!', '', ''])

print func_name(['', ''])

Upvotes: 2

Jimmys
Jimmys

Reputation: 377

check an example:

x = ["don't", '', 13] 

while '' in x:
    x.remove('')

assert x == ["don't", 13]

Upvotes: 0

Elazar
Elazar

Reputation: 21655

Your problem is that the list is shortened, but the indices are still iterated as if it's the original list.

There are better ways of implementing this (see other answers), but to fix your implementation, you can iterate in reverse order thus avoiding the "overflow":

def remove_empty(s):
   for k in reversed(range(len(s))):
       if s[k] == '':
           del s[k]

This only works in case where you remove at most one element at each iteration.

Note that this mutates s in place.

>>> a = ['Title','','This','is','a','link','.']
>>> remove_empty(a)
>>> a
['Title','This','is','a','link','.']

Upvotes: 1

Related Questions