In this Python code snippet, we present a program that removes the ith occurrence of a given word from a list, where the word may occur multiple times. The program takes a list as input and removes the ith occurrence of the specified word. To achieve this, we traverse the list using a loop and keep track of the number of occurrences of the given word. Once the ith occurrence is found, we remove it from the list using the del
statement and break out of the loop. If the ith occurrence does not exist in the list, the original list is returned.
Python program to remove nth occurrence of the given word list
Here’s a Python program that removes the nth occurrence of a given word from a list, where words can repeat:
def remove_nth_occurrence(lst, word, n): """ Removes the nth occurrence of a given word from a list. Args: lst (list): The input list. word (str): The word to remove. n (int): The nth occurrence to remove. Returns: The updated list with the nth occurrence of the given word removed. If the nth occurrence does not exist, returns the original list. """ count = 0 for i, w in enumerate(lst): if w == word: count += 1 if count == n: del lst[i] break return lst
Here’s an example of how to use the remove_nth_occurrence
function:
lst = ['apple', 'banana', 'orange', 'banana', 'grape', 'banana'] word = 'banana' n = 2 result = remove_nth_occurrence(lst, word, n) print(result) # Output: ['apple', 'banana', 'orange', 'grape', 'banana']
In this example, the second occurrence of the word ‘banana’ is removed from the list lst
, resulting in the updated list ['apple', 'banana', 'orange', 'grape', 'banana']
.