How do i remove a specific word from a list in python?

I have done my code this far but it is not working properly with remove()..can anyone help me..

'''
Created on Apr 21, 2015

@author: Pallavi
'''
from pip._vendor.distlib.compat import raw_input
print ("Enter Query")
str=raw_input()  

fo = open("stopwords.txt", "r+")
str1 = fo.read();
list=str1.split("\n");
fo.close()
words=str.split(" ");
for i in range(0,len(words)):
    for j in range(0,len(list)):
        if(list[j]==words[i]):
            print(words[i])
            words.remove(words(i))

Here is the error:

Enter Query
let them cry try diesd
let them try
Traceback (most recent call last):
  File "C:\Users\Pallavi\workspace\py\src\parser.py", line 17, in 
    if(list[j]==words[i]):
IndexError: list index out of range

asked Apr 21, 2015 at 11:38

How do i remove a specific word from a list in python?

3

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]

answered Apr 21, 2015 at 11:48

Francis ColasFrancis Colas

3,1212 gold badges24 silver badges31 bronze badges

2

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))

answered Oct 9, 2019 at 13:34

''' call this script in a Bash Konsole like so:    python  reject.py
    purpose of this script: remove certain words from a list of words ,
    e.g. remove invalid packages in a request-list using 
    a list of rejected packages from the logfile, 
    say on https://fai-project.org/FAIme/#
    remove trailing spaces e.g. with KDE Kate in wordlist like so:

kate: remove-trailing-space on; BOM off;
'''
with open("rejects", "r+")       as fooo   :
    stwf    = fooo.read()
toreject    = stwf.split("\n")

with open("wordlist", "r+")      as bar    :
  woL       = bar.read()
words       = woL.split("\n")

new_words = [word for word in words if word not in toreject]
with open("cleaned", "w+")       as foobar :
    for ii in new_words:
        foobar.write("%s\n" % ii)

one more easy way to remove words from the list is to convert 2 lists into the set and do a subtraction btw the list.

words = ['a', 'b', 'a', 'c', 'd']
words = set(words)
stopwords = ['a', 'c']
stopwords = set(stopwords)
final_list = words - stopwords
final_list = list(final_list)

answered Apr 22, 2020 at 13:08

1

Last update on August 19 2022 21:51:47 (UTC/GMT +8 hours)

Python List: Exercise - 148 with Solution

Write a Python program to remove specific words from a given list.

Sample Solution:

Python Code:

def remove_words(list1, remove_words):
    for word in list(list1):
        if word in remove_words:
            list1.remove(word)
    return list1        
colors = ['red', 'green', 'blue', 'white', 'black', 'orange']
remove_colors = ['white', 'orange']
print("Original list:")
print(colors)
print("\nRemove words:")
print(remove_colors)
print("\nAfter removing the specified words from the said list:")
print(remove_words(colors, remove_colors))

Sample Output:

Original list:
['red', 'green', 'blue', 'white', 'black', 'orange']

Remove words:
['white', 'orange']

After removing the specified words from the said list:
['red', 'green', 'blue', 'black']

Flowchart:

How do i remove a specific word from a list in python?

Visualize Python code execution:

The following tool visualize what the computer is doing step-by-step as it executes the said program:

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

Previous: Write a Python program to interleave two given list into another list randomly.
Next: Write a Python program to get all possible combinations of the elements of a given list.

Python: Tips of the Day

Checking whether all elements in the sequence are Truthful:

>>> all(a % 2==0 for a in range(0,10,2))
True

How do I remove a specific value from a list in Python?

How to Remove an Element from a List Using the remove() Method in Python. To remove an element from a list using the remove() method, specify the value of that element and pass it as an argument to the method. remove() will search the list to find it and remove it.

How do I remove a specific string from a list in Python?

Use list. remove() to remove a string from a list. Call list. remove(x) to remove the first occurrence of x in the list.

How do I remove a specific element from a list?

remove() can perform the task of removal of list element. Its removal is inplace and does not require extra space. But the drawback that it faces is that it just removes the first occurrence from the list. All the other occurrences are not deleted hence only useful if list doesn't contain duplicates.

How do I remove a specific value from a list index?

You can use the pop() method to remove specific elements of a list. pop() method takes the index value as a parameter and removes the element at the specified index. Therefore, a[2] contains 3 and pop() removes and returns the same as output. You can also use negative index values.