
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Remove Nth Occurrence of a Word in a List in Python
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 the counter by 1. If the count and the specific occurrence match, then the specific element from the list can be deleted.
Below is a demonstration of the same −
Example
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']
Explanation
A method named ‘remove_word’ is defined, which takes the list, a word, and a value for ‘n’ as a parameter.
A ’count’ value is initialized to 0.
The list is iterated over, and it is checked to see if the element in the list matches a specific word.
If they match, the count variable is incremented.
If this count variable is equal to a value ‘n’, then the element from the list is deleted.
It is used using the ‘del’ keyword.
A list of strings is defined and displayed on the console.
The method is called by passing relevant parameters.
The output is displayed on the console.