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 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 Tutorials
Recommended:-Python Program to Calculate Simple Interest
Recommended:-Python Program to Find Average of n Numbers
Recommended:-Python Program to ASCII Value of Character
Recommended:-Python Program to Calculate Compound Interest
Recommended:-Python Program to Check Leap Year
Recommended:-Python Program To Print Number Pattern
Recommended:-Python Program to Print Star Pattern
Recommended:-Python Program Calculate Sum of n Numbers
Recommended:-Python Program to Reverse Numbers
Recommended:-Python Program to Find Largest of n Numbers
Recommended:-Python Program to Find Power of Number
Recommended:-Python Program to Print Prime Number From 1 to N
Recommended:-Python Program to Find Square Root of Number
Recommended:-Python Program to Find Cube of Number
Recommended:-Python Palindrome Program
Recommended:-Python Program to Count Set Bits in a Number
Recommended:-Python Program for BMI Calculation
Recommended:-Python Program to Find Out Absolute Value
Recommended:-Python Random Number Generator Code