How to remove case insensitive words from a list?

I have a list called words, containing words that can be in upper or lower case, or some combination of them. Then I have another list called stopwords, which contains only lowercase words. Now I want to go through each word in stopwordsand delete all instances of this word from wordscase insensitive, but I do not know how to do it. Suggestions?

Example:

words = ['This', 'is', 'a', 'test', 'string']
stopwords = ['this', 'test']

for stopword in stopwords:
    if stopword in words:
        words.remove(stopword);

print words

Shown result: ['This', 'is', 'a', 'string']

The correct return should be as follows: ['is', 'a', 'string']

+4
source share
1 answer

Make your word lowercase so you don’t have to worry about casing:

words = ['This', 'is', 'a', 'test', 'string']
stopwords = {'this', 'test'}

print([i for i in words if i.lower() not in stopwords])

Outputs:

['is', 'a', 'string']

@cricket_007 ( @chepner ), -, . , .

+9

All Articles