How to remove words from a list in python

As an observation, this could be another elegant way to do it:

new_words = list(filter(lambda w: w not in stop_words, initial_words))

The errors you have (besides my other comments) are because you're modifying a list while iterating over it. But you take the length of the list at the start, thus, after you've removed some elements, you cannot access the last positions.

I would do it this way:

words = ['a', 'b', 'a', 'c', 'd']
stopwords = ['a', 'c']
for word in list(words):  # iterating on a copy since removing will mess things up
    if word in stopwords:
        words.remove(word)

An even more pythonic way using list comprehensions:

new_words = [word for word in words if word not in stopwords]

Tags:

Python 3.X