0

I'm working on a beginner project to detect anagrams. Part of it is removing all the spaces from each word. To do this, I'm using

for i in list1:
        if(i == " "):
            list1.remove(i)

  for i in list2:
        if(i == " "):
            list2.remove(i)

It removes every space, except when two or more spaces are adjacent, and then it always leaves one space

  • You can achieve the same result with string.strip() – Leo Nov 04 '21 at 18:10
  • These are great recommendations, but they're still not addressing the underlying mechanism of the script that is failing OP. – Yehuda Nov 04 '21 at 18:10
  • @Yehuda, the dup that I linked to is addressing exactly the issue OP is facing. – buran Nov 04 '21 at 18:11
  • Please, provide [mre], incl. sample input. – buran Nov 04 '21 at 18:12
  • 3
    The problem is that when the ith element of list1 is removed, in the next iteration i+1 is being evaluated while it should re-evaluate the element i. – Mahdiar Nov 04 '21 at 18:13
  • You should not modify a list you are iterating over within the looping block. Best to build up a new list of what you want to save, or a list of indexes to delete, and delete them from highest to lowest in another loop. – RufusVS Nov 04 '21 at 18:19

2 Answers2

1

The issue origins from the fact that you're manipulating a list while iterating through it. When you delete a space at a certain index, the next character now becomes this index, but as your iterating you increment the index and therefore skip this character.

So you either have to iterate through the whole string and manipulate afterwards or also manipulate your iterator while iterating. The latter is not possible with for i in list.

po.pe
  • 1,047
  • 1
  • 12
  • 27
0

Try implementing this to solve the one space left issue:

list = [' hi', '   hello ', '  how   are    you']
d = []
for element in range(0,len(list)):
      d.append("".join(list[element].split())) 
xBatmanx
  • 80
  • 7