Python program to remove nth occurrences of a given word from list; In this python post, we would love to share with you the python program takes a list and removes the ith occurrence of the given word in the list where words can repeat.
Python program to remove nth occurrence of the given word list
- To allow the user to input a number of elements in the list and store it in a variable.
- 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 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'}
Recommended Python Programs
- Python Print List Elements in Different Way
- How to Input List From User in Python
- Python Add and Remove Elements From List
- Python: Add/Insert Element at Specified Index in List
- Python Program to Sort List in Ascending and Descending Order
- Python to Find the Differences of Two Lists
- Python to Find Minimum and Maximum Elements of List
- Python Programs to Split Even and Odd Numbers in Separate List
- Python Program to Create Two Lists with First Half and Second Half Elements of Given List
- Python Program to Swap Two Elements in a List
- Python Program to Reverse List
- How To Select Random Item From A List In Python