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

Time:11-11

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

CodePudding user response:

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']]
  • Related