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]
Answer from Francis Colas on Stack Overflow
🌐
Reddit
reddit.com › r/learnpython › how to remove words in a list from a list of strings?
r/learnpython on Reddit: How to remove words in a list from a list of strings?
April 6, 2022 -

I have a list of strings:

list_strings = ['[power, brilliant, evil]',  '[shock, poetic, watch, lift]']

I want to remove words that occur in the following list:

remove = ['evil', 'money', 'poetic', 'lift']

The result I am seeking is:

result = ['[power, brilliant]',  '[shock, watch]']

It's also important that the words that remain stay in a list themselves e.g., [power, brilliant].

What I have tried:

# attempt 1:
list_strings = ['[power, brilliant, evil]',  '[shock, poetic, watch, lift]']
remove = ['evil', 'money', 'poetic', 'lift']
result = [' '.join(w for w in str(list_strings).split() if w.lower() not in remove)
         for place in places
         ]
print(result)

# attempt 2:
list_strings = ['[power, brilliant, evil]',  '[shock, poetic, watch, lift]']
remove = ['evil', 'money', 'poetic', 'lift']

for each in list_strings:
    for i in remove:
        x = each.replace(i, "")
        print(x)
Discussions

Removing words from list in python - Stack Overflow
I have a list 'abc' (strings) and I am trying to remove some words present in list 'stop' from the list 'abc' and all the digits present in abc. abc=[ 'issues in performance 421', 'how are you d... More on stackoverflow.com
🌐 stackoverflow.com
July 13, 2018
web scraping - Removing words from python lists? - Stack Overflow
I am a complete noob in python and web scraping and have ran into some issues quite early. I have been able to scrape a Dutch news website their titles and splitting the words. Now my objective is to remove certain words from the results. For instance I don't want word like "het" and "om" in the list... More on stackoverflow.com
🌐 stackoverflow.com
string - Python script for removing words with certain letters in a list - Stack Overflow
I am trying to run a simple python script that removes certain words containing certain letters originally part of a string, correctly separated into a list of words. I re-checked the code multiple... More on stackoverflow.com
🌐 stackoverflow.com
March 5, 2022
Python- How To Remove Elements From a List Containing a Specific Word - Stack Overflow
I want to remove elements from a list containing a keyword. For example- list1= [ 'one', 'one-test', 'two', 'two-test', 'three', 'three-test'] I want to remove all elements in this list that conta... More on stackoverflow.com
🌐 stackoverflow.com
🌐
w3resource
w3resource.com › python-exercises › list › python-data-type-list-exercise-148.php
Python: Remove specific words from a given list - w3resource
Python List Exercises, Practice and Solution: Write a Python program to remove specific words from a given list.
🌐
w3resource
w3resource.com › python-exercises › list › python-data-type-list-exercise-127.php
Python: Remove words from a given list of strings containing a character or string - w3resource
# Define a function 'remove_words' that removes specific words from a list of strings def remove_words(in_list, char_list): # Initialize an empty list to store the modified strings new_list = [] # Iterate through each line in 'in_list' for line in in_list: # Split the line into words and join only those words that don't contain any phrase from 'char_list' new_words = ' '.join([word for word in line.split() if not any([phrase in word for phrase in char_list])]) # Append the modified line to the 'new_list' new_list.append(new_words) return new_list # Create a list of strings 'str_list' str_list
🌐
Medium
medium.com › @virjflores › removing-words-from-a-sentence-given-they-are-present-in-another-list-in-python-and-other-life-301c75653d63
Removing words from a sentence given they are present in another list in Python — and other life lessons | by Virj Flores | Medium
August 27, 2023 - Given two different lists A and B, remove the items in A that are present in B. Here’s a function that implements this through list comprehension: def drop_words(phrase, disallowed_wordlist): """ Remove words from the phrase or sentence that ...
Find elsewhere
🌐
Quora
quora.com › How-do-you-remove-a-specific-word-from-a-list-in-Python
How to remove a specific word from a list in Python - Quora
Answer (1 of 2): Deletion Operation on Lists: Python provides operator(s) for deleting/removing an item from a list. There are many methods for deletion. * If Index is known, you can use ‘pop( )’ or ‘del statement’. pop( ) function: It removes the element from the specified index and ...
🌐
GeeksforGeeks
geeksforgeeks.org › python-remove-words-containing-list-characters
Remove words containing list characters – Python | GeeksforGeeks
December 5, 2024 - List comprehension: Iterates over ... from remove_chars. any(): Ensures that words with the specified characters are excluded. ... Sometimes, while working with Python lists, we can have problem in which we need to perform the task of removing all the elements of list which contain at least one character of String. This can have application in day-day programming. Lets discuss certain ways in which ...
🌐
GeeksforGeeks
geeksforgeeks.org › python › python-remove-words-containing-list-characters
Remove words containing list characters - Python - GeeksforGeeks
July 12, 2025 - If a word contains any of those characters then it will be excluded from the final result. ... a = ['gfg', 'is', 'best', 'for', 'geeks'] # List of characters to check for remove_chars = ['g', 'e'] # Initialize an empty list to store result res = [] # Loop through each word for word in a: # Check if word contains any of characters from remove_chars if not any(char in word for char in remove_chars): res.append(word) print(res)
🌐
Bobby Hadz
bobbyhadz.com › blog › python-remove-list-of-words-from-string
Blog | bobbyhadz
August 7, 2022 - Articles on AWS, Serverless, React.js and Web Development - solving problems and automating tasks.
🌐
Stack Overflow
stackoverflow.com › questions › 71359595 › python-script-for-removing-words-with-certain-letters-in-a-list
string - Python script for removing words with certain letters in a list - Stack Overflow
March 5, 2022 - s = """aline amine avine azine brine chine cline coine crine daine dwine exine ezine faine feine foine gwine imine koine laine Maine opine ovine peine quine raine rhine saine seine shine spine swine thine trine tsine twine Udine urine whine""" words = list(s.split()) for i in words: if "s" in i: words.remove(i) elif "a" in i: words.remove(i) elif "d" in i: words.remove(i) elif "w" in i: words.remove(i) elif "u" in i: words.remove(i) print(words) ... In general, it's a bad idea to remove elements from a list as you're iterating over it, as the memory is shifting as you're trying to access it.
Top answer
1 of 1
5

You currently have to loop over all exclude words to check if it is equal to the current word. If your exclude was a set, you could just do if j in exclude. This change alone should speed up your code a lot (how much depends on how large your list of exclude words actually is).

In addition, you could simplify getting the exclude words:

from collections import Counter
form itertools import takewhile

THRESHOLD = 25

words = Counter(whatever_generates_your_words())
exclude = set(t[0] for t in takewhile(lambda t: t[1] <= THRESHOLD,
                                      reversed(words.most_common())))

This uses the fact that collections.Counter.most_common is sorted by frequency, so reversing it starts with the least common words. itertools.takewhile stops taking when the condition is no longer true, so you don't need to go through all words in the Counter.

For the filtering you should probably use some list comprehensions. All three of the following functions are doing the same thing:

from itertools import filterfalse

def remove_nonfrequent(note):
    sentences = []
    for sentence in note.split('. '):
        sentence_ = []
        for word in sentence:
            if word not in exclude:
                sentence_.append(word)
        if sentence:
            sentences.append(" ".join(sentence))
    return ". ".join(sentences)

def remove_nonfrequent(note):
    return ". ".join(" ".join(filterfalse(exclude.__contains__,
                              sentence.split(" ")))
                     for sentence in note.split('. '))
                     if sentence)

def remove_nonfrequent(note):        
    return ". ".join(" ".join(word for word in sentence.split(" ")
                              if word not in exclude)
                     for sentence in note.split('. ') if sentence)

I personally prefer the last one, as it is the most readable one to me.

Note that Python has an official style-guide, PEP8, which recommends using 4 spaces as indentation and surrounding operators with spaces.


Since you are using this function with pandas later, a different approach might actually be faster. There is a pd.Series.replace method that can take a dictionary of replacements. You can use it like this:

from itertools import repeat

replacements = dict(zip((fr'\b{word}\b' for word in exclude), repeat("")))
df.NOTES.replace(replacements, regex=True, inplace=True)
df.NOTES.replace({r' +': ' ', r' +\.': '.'}, regex=True, inplace=True)

The first replace does all the word replacements (using \b to ensure only complete words are replaced), while the latter one fixes multiple spaces and spaces before a period.

🌐
Reddit
reddit.com › r/learnpython › how do i remove certain words from a string?
r/learnpython on Reddit: How do I remove certain words from a string?
December 29, 2020 -

I am making my first hangman game, I finished everything and now I want to add lots of words to a txt file and import them to the hangman file. I came against a problem however, some of the words I copied and pasted were short and so I wanted to create a small function that deletes all the short word in the Long string.

I started by making the list of words into an actual list

hang = words.split() #now all my words are in a list, then...
for item in hang:
    if len(item) < 2:
        hang.remove(item)
print(hang) #perfect all the short words have been removed. 

#But now I want to change the hang from being a type list to a normal list of words in string, not an actual list. 

Is there a way I can do that exactly?

Thank you.

🌐
Programiz
programiz.com › python-programming › methods › list › remove
Python List remove()
# 'dog' is removed animals.remove('dog') # Updated animals list print('Updated animals list: ', animals) ... Here, only the first occurrence of element 'dog' is removed from the list.
🌐
CodeScracker
codescracker.com › python › program › python-program-remove-word-from-sentence.htm
Python Program to Remove Word from Sentence
Here is its sample run with user input, welcome to codescracker to learn Python as string and to as word to delete: ... This is the modified version of previous program. The join() method in this program used in a way that, the list newtext is converted into a string:
Top answer
1 of 2
1

You can use a regular expression with word boundaries.

pattern = re.compile('|'.join(rf'\b{re.escape(w)}\b' for w in word_list))
def remove_w(text):
    return pattern.sub('', text)

Alternatively, use str.split to separate into words delimited by spaces, remove the words exactly matching one of those in the set, then join it back together.

def remove_w(text):
    return ' '.join(w for w in text.split() if w not in word_list)
2 of 2
0

You can use regular expressions to remove whole words from the text while taking care not to remove parts of other words. In your specific case, you can use the re module to achieve that:

import re

word_list = {"the", "mind", "pen"}
word_pattern = r"(\s?)\b(?:" + "|".join(re.escape(word) for word in word_list) + r")\b"
pattern = re.compile(word_pattern)

def remove_w(text):
    return pattern.sub("", text)

text = "A pencil is over a thermometer with mind itself."
result = remove_w(text)
print(result)

The output will be:

A pencil is over a thermometer with itself.

Explanation:

  1. re.escape(word): Escapes any characters that might have a special meaning in regular expressions, like ., ?, *, etc.
  2. (\s?): Matches any whitespace and ? to make it optional.
  3. '|'.join(...): Joins the words together with the regex OR pattern |.
  4. \b: Matches the empty string but only at the beginning or end of a word.
  5. pattern.sub('', text): Replaces the matched words in the text with an empty string.

This approach should work efficiently even for large articles, as the regular expression engine is optimized for text processing tasks like these.