Python program to remove Nth occurrence of the given word

Given a list of words in Python, the task is to remove the Nth occurrence of the given word in that list.

Examples:

Input: list - ["geeks", "for", "geeks"]
       word = geeks, N = 2
Output: list - ["geeks", "for"]

Input: list - ["can", "you",  "can", "a", "can" "?"]
       word = can, N = 1
Output: list - ["you",  "can", "a", "can" "?"]

 

Approach #1: By taking another list.

Make a new list, say newList. Iterate the elements in the list and check if the word to be removed matches the element and the occurrence number, otherwise, append the element to newList.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to remove Nth 
# occurrence of the given word
  
# Function to remove Ith word
def RemoveIthWord(lst, word, N):
    newList = []
    count = 0
  
    # iterate the elements
    for i in lst:
        if(i == word):
            count = count + 1
            if(count != N):
                newList.append(i)
        else:
            newList.append(i)
              
    lst = newList
      
    if count == 0:
        print("Item not found")
    else:
        print("Updated list is: ", lst)    
      
    return newList
  
# Driver code
list = ["geeks", "for", "geeks"]
word = "geeks"
N = 2
  
RemoveIthWord(list, word, N)

chevron_right


Output :

Updated list is:  ['geeks', 'for']

 
Approach #2: Remove from the list itself.

Instead of making a new list, delete the matching element from the list itself. Iterate the elements in the list and check if the word to be removed matches the element and the occurrence number, If yes delete that item and return true. If True is returned, print List otherwise, print “Item not Found”.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to remove Nth 
# occurrence of the given word
  
# Function to remove Ith word
def RemoveIthWord(list, word, N):
    count = 0
      
    for i in range(0, len(list)):
        if (list[i] == word):
            count = count + 1
              
            if(count == N):
                del(list[i])
                return True
                  
    return False
  
# Driver code
list = ['geeks', 'for', 'geeks']
word = 'geeks'
N = 2
  
flag = RemoveIthWord(list, word, N)
  
if (flag == True):
    print("Updated list is: ", list)
else:
    print("Item not Updated"

chevron_right


Output :

Updated list is:  ['geeks', 'for']


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.