Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Python Program to Remove the nth Occurrence of the Given Word in a List where Words can Repeat
When it is required to remove a specific occurrence of a given word in a list of words, given that the words can be repeated, a method can be defined that iterates through the list and increments a counter. If the count matches the specific occurrence, then that element can be deleted from the list.
Example
Below is a demonstration of removing the nth occurrence of a word from a list ?
def remove_word(my_list, my_word, N):
count = 0
for i in range(0, len(my_list)):
if (my_list[i] == my_word):
count = count + 1
if(count == N):
del(my_list[i])
return True
return False
my_list = ['Harry', 'Jane', 'Will', 'Rob', 'Harry']
print("The list is :")
print(my_list)
my_word = 'Harry'
N = 2
flag_val = remove_word(my_list, my_word, N)
if (flag_val == True):
print("The updated list is: ", my_list)
else:
print("Item hasn't been updated")
Output
The list is : ['Harry', 'Jane', 'Will', 'Rob', 'Harry'] The updated list is: ['Harry', 'Jane', 'Will', 'Rob']
How It Works
The function works by maintaining a counter that tracks how many times the target word has been encountered. When the counter reaches the desired occurrence number (N), the function deletes that element and returns True. If the nth occurrence is not found, it returns False.
Alternative Approach Using enumerate()
Here's a cleaner version using enumerate() for better readability ?
def remove_nth_occurrence(words, target_word, n):
count = 0
for i, word in enumerate(words):
if word == target_word:
count += 1
if count == n:
words.pop(i)
return True
return False
# Example usage
words = ['apple', 'banana', 'apple', 'cherry', 'apple']
print("Original list:", words)
result = remove_nth_occurrence(words, 'apple', 2)
print("Removed 2nd occurrence:", result)
print("Updated list:", words)
Original list: ['apple', 'banana', 'apple', 'cherry', 'apple'] Removed 2nd occurrence: True Updated list: ['apple', 'banana', 'cherry', 'apple']
Key Points
The function modifies the original list directly
Returns
Trueif the nth occurrence was found and removedReturns
Falseif the nth occurrence doesn't existThe counter only increments when the target word is found
Conclusion
This approach efficiently removes the nth occurrence of a word from a list by tracking occurrences with a counter. The function provides feedback on whether the removal was successful, making it useful for validation in larger programs.
