ValueError: list.remove(x): x not in list when removing strings in a list of a list

Question:

I have a list of list : the sublist conatins strings. I would like to remove elements from this sublist if they are in a set of Stopword that I created. So I iterate through the sublist and If the string is in the set than I remove it using .remove(). But I get the error that the word is not in the list which is incorrect

here is my code

stopwords = set(["s", "a", "about", "above" ])
MM=[["s","mam"],["about","645"]]

for i in MM:
    for j in i:
        if j in stopwords:
            MM.remove(j)
        
        
MM
Asked By: AtotheF

||

Answers:

You must remove the word inside the sublist not on the original list.

stopwords = set(["s", "a", "about", "above" ])
MM=[["s","mam"],["about","645"]]

for idx, i in enumerate(MM):
    for j in i:
        if j in stopwords:
            MM[idx].remove(j)

Output:

[['mam'], ['645']]
Answered By: Will
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.