Python program to remove Nth occurrence of the given wordGiven a list of words in Python, the task is to remove the Nth occurrence of the given word in that list. Show
Recommended: Please try your approach on {IDE} first, before moving on to the solution.
Python3
Output : Updated list is: ['geeks', 'for']
Python3
Output : Approach #3: Remove from the list using pop(). Python3
Output : new list is : ['he', 'is', 'ankit', 'is', 'raj', 'ankit raj']Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics. To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course
Article Tags :
Python Python Programs
Python list-programs IntroductionIn this section of python programming, we will understand the code to eliminate the nth occurrence of the given element from the list. on Oct 13 2021 Comment0 Add a Grepper Answer Python answers related to “python remove second occurrence of character in string”
Python queries related to “python remove second occurrence of character in string”
Python program to remove nth occurrence of the given word list
# python program to remove nth occurrence of the given word
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=input("Enter element" + str(x+1) + ":")
a.append(element)
print(a)
c=[]
count=0
b=input("Enter word to remove: ")
n=int(input("Enter the occurrence to remove: "))
for i in a:
if(i==b):
count=count+1
if(count!=n):
c.append(i)
else:
c.append(i)
if(count==0):
print("Item not found ")
else:
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'}1. Using list.remove() functionlist.remove(x) removes the first occurrence of value x from the list, but it fails to remove all occurrences of value x from the list.
DownloadRun Code
DownloadRun Code |