Python Program to Remove Nth Occurrence of Given Word in List

Python program to remove the first occurrence of a specified element from an array or list; Through this tutorial, i am going to show you how to removes the n th occurrence of the given word in the list where words can repeat.

Python program to remove nth occurrence of the given word list

  • To get input number of elements in the list or array and store it in a variable from user in program.
  • Accept the values into the list using a for loop and insert them into the python list.
  • Use a for loop to traverse through the elements in the list.
  • Then use an if statement to check if the word to be removed matches the element and the occurrence number and otherwise, it appends the element to another list.
  • The number of repetitions along with the updated list and distinct elements is printed.
# python program to remove nth occurrence of the given word
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
    element=input("Enter element" + str(x+1) + ":")
b=input("Enter word to remove: ")
n=int(input("Enter the occurrence to remove: "))
for i in a:
    print("Item not found ")
    print("The number of repetitions is: ",count)
    print("Updated list is: ",c)
    print("The distinct elements are: ",set(a))

After executing the program, the output will be:

Enter the number of elements in list: 5
Enter element1: test
Enter element2: test
Enter element3: my
Enter element4: world
Enter element5: world
['test', 'test', 'my', 'world', 'world']
Enter word to remove:  world
Enter the occurrence to remove:  4
The number of repetitions is:  2
Updated list is:  ['test', 'test', 'my', 'world', 'world']
The distinct elements are:  {'test', 'world', 'my'}

Recommended Python Tutorials

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *