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.
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”.
Output :
Updated list is: ['geeks', 'for']
Approach #3: Remove from the list using pop().
Instead of creating a new list and using if/else statement we can pop the matching element from the list using pop( ). We need to use an additional counter to keep track of the index.
Why we need an index ? because pop( ) needs index to pass inside i.e pop(index).
Output :
new list is : ['he', 'is', 'ankit', 'is', 'raj', 'ankit raj']
No comments:
Post a Comment
Your feedback is highly appreciated and will help us to improve our content.