Python program to remove one occurrence of a word in a list
Python program to remove the kth occurrence of a word in list :
In this tutorial, we will learn how to remove the kth occurrence of a word in a given list. The list is given. It contains words and most words are repeated. We will create one function to remove the kth occurrence of one word if it is available in the list. If it is not available, it will show one message.
Python program :
The python program is as like below :
# 1 def removeWord(list, word, k): n = 0 #2 for i in range(0, len(list)): if(list[i] == word): n += 1 #3 if(n == k): del(list[i]) return True return False #4 list = ['hello', 'world', 'hello', 'world', 'hello', 'world'] #5 if(removeWord(list, input("Enter a word : "), int(input("Enter k : ")))): print("The list is updated : ", list) else: print("The given word is not found")
The commented numbers in the above program denote the step numbers below :
- removeWord function is used to remove the kth occurrence of a word in a given list. It takes three arguments : the list, word to remove and the value of k.
- n variable is initialized to 0. This variable will hold the current count of the word. Using one for loop, we are iterating through the list of words one by one. If the current value is equal to the given word, increase the value of n by 1.
- Check if the value of n is equal to k or not. If yes, delete the element of index i and return True. Else, return False once the loop ends.
- list is the given list of words.
- We are taking the word and k as input from the user. If the word is found, it prints the updated list. Else, it prints one message that the word is not found.
Sample Output :
Enter a word : hfdal Enter k : 2 The given word is not found Enter a word : hello Enter k : 3 The list is updated : ['hello', 'world', 'hello', 'world', 'world']
Similar tutorials :
- Python program to iterate over the list in reverse order
- Python program to remove all occurrence of a value from a list
- How to remove item from a list in python
- Python program to remove all duplicate elements from a list
- Python program to find out the sum of odd and even numbers in a list
- Python program to swap the first and the last element of a list