-3

If I loop through the list like this:

print(b)
for i in list:
    if i == '':
        b.remove(i)
print(b)

The empty strings remain in the output:

['','123','','','','','1','','1232','']
['123','1','','1232','']

How can I remove them all?

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
JustinHsu
  • 13
  • 1
  • 4

2 Answers2

3

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.

axolotl
  • 93
  • 6
  • 2
    Alternatives: `list(filter(None, b))`: `filter(None, ...)` is a special feature which removes all falsy items, also your v0 has the predicate reversed. The third version is not great because `b.remove(i)` will traverse the entire list rather than just remove the item. A "better" imperative version is to iterate in reverse getting the index, and `del` at that index. Doing it backwards ensures items don't move as you modify the list. And I think you can do a reverse removal from lists *while iterating* so you don't have to copy the list beforehand. – Masklinn Apr 21 '20 at 08:04
  • Thank you :) I implemented your suggestions. – axolotl Apr 21 '20 at 08:12
0

I think axolotl's answer is correct, but you can use this for solving your problem too:

a = 'a123aaaaa1aa1232a'
b = a.split('a')
lst = []
for i in b:
    if i != '':
        lst.append(i)
print(lst)

Note for being better programmer: Don't name your variables something easy like a and b, instead, use a name that make sense with your variable!

  • This adds a too many steps, since the solution can easily be one line. I would recommend using a simpler solution since the code will be more readable and easy to understand at quick glance in the future. – Jeff Gruenbaum Sep 22 '21 at 17:11