0

I've got the following simple for loop.

for word in text:
    if word in stopword_list:
       text.remove(word)

So far it has worked for removing any item found on the stopword_list. However if two of these items are next to each other, it ignores the second. For example:

stopword_list = (['i', 'am'])

'i' or 'am' individually will be removed

(['I', 'x', 'y', 'am']) will remove both 'I' and 'am'

(['I', 'am']) will remove 'I' but not 'am'

If I run the list itself through the loop, it removes every other word.

Why is this happening?

Random Davis
  • 6,662
  • 4
  • 14
  • 24
  • 2
    "Why is this happening?" - because you're modifying the same collection you're currently iterating. A classic mistake in many environments. – Sergio Tulentsev Dec 03 '21 at 20:34
  • 1
    If you create another instance of the list and use one to iterate and another one to remove, then you will not have such problems. – Coke Dec 03 '21 at 20:36
  • Try a list comprehension [ word for word in text if word not in stopword_list ] – Mark Lavin Dec 03 '21 at 20:44

0 Answers0