Python program to remove Nth occurrence of the given word
Last Updated :
22 Apr, 2023
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.
Python3
def RemoveIthWord(lst, word, N):
newList = []
count = 0
for i in lst:
if (i = = word):
count = count + 1
if (count ! = N):
newList.append(i)
else :
newList.append(i)
lst = newList
if count = = 0 :
print ( "Item not found" )
else :
print ( "Updated list is: " , lst)
return newList
list = [ "geeks" , "for" , "geeks" ]
word = "geeks"
N = 2
RemoveIthWord( list , word, N)
|
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”.
Python3
def RemoveIthWord( list , word, N):
count = 0
for i in range ( 0 , len ( list )):
if ( list [i] = = word):
count = count + 1
if (count = = N):
del ( list [i])
return True
return False
list = [ 'geeks' , 'for' , 'geeks' ]
word = 'geeks'
N = 2
flag = RemoveIthWord( list , word, N)
if (flag = = True ):
print ( "Updated list is: " , list )
else :
print ( "Item not Updated" )
|
Output
Updated list is: ['geeks', 'for']
Approach #3: Remove from the list using pop().
Instead of creating a new list and using an 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 do we need an index? because pop( ) needs index to pass inside i.e pop(index).
Python3
def omit(list1, word, n1):
count = 0
index = 0
for i in list1:
index + = 1
if i = = word:
count + = 1
if count = = n1:
list1.pop(index - 1 )
return list1
list1 = [ "he" , "is" , "ankit" , "is" ,
"raj" , "is" , "ankit raj" ]
word = "is"
n1 = 3
print ( "new list is :" , omit(list1, word, n1))
|
Output
new list is : ['he', 'is', 'ankit', 'is', 'raj', 'ankit raj']
Time complexity: O(n) where n is the length of the input list.
Auxiliary space: O(1)
because it only uses a fixed amount of extra space to store the count and index variables, and no additional data structures are created.
Approach #4: Using List Comprehension
- Step 1: Initialize a variable count to 0.
- Step 2: Use list comprehension to create a new list with elements of the original list except for the n1th occurrence of word.
a. If the current element is not equal to word, add it to the new list.
b. If the current element is equal to word, increment the count variable. If the count is equal to n1, skip adding this element to the new list.
- Step 3: Return the new list.
Python3
def omit(list1, word, n1):
count = 0
new_list = []
for i in list1:
if i ! = word or (i = = word and count ! = n1):
new_list.append(i)
if i = = word:
count + = 1
return new_list
list1 = [ "he" , "is" , "ankit" , "is" , "raj" , "is" , "ankit raj" ]
word = "is"
n1 = 3
print ( "new list is :" , omit(list1, word, n1))
|
Output
new list is : ['he', 'is', 'ankit', 'is', 'raj', 'is', 'ankit raj']
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(n), as we are creating a new list to store the filtered elements.
Method 5: recursive approach. Here are the steps for the recursive approach:
- Define the function omit(list1, word, n1).
- Check if the list is empty. If it is, return an empty list.
- Check if the first element of the list is the word and if the count of the word is less than n1. If both conditions are true, remove the first element and recursively call the function with the updated list, the same word, and n1 minus 1.
- If the first element of the list is not the word or the count of the word has reached n1, append the first element to a new list and recursively call the function with the rest of the list, the same word, and the same n1.
- Return the new list.
Python3
def omit(list1, word, n1):
if not list1:
return []
if list1[ 0 ] = = word and n1 > 0 :
return omit(list1[ 1 :], word, n1 - 1 )
return [list1[ 0 ]] + omit(list1[ 1 :], word, n1)
list1 = [ "he" , "is" , "ankit" , "is" , "raj" , "is" , "ankit raj" ]
word = "is"
n1 = 3
print ( "new list is :" , omit(list1, word, n1))
|
Output
new list is : ['he', 'ankit', 'raj', 'ankit raj']
Time complexity: O(n), where n is the length of the input list, as the function needs to iterate through the entire list once.
Auxiliary space: O(n), as the function creates a new list to store the elements that are not removed.
Approach #6: Using a Generator Function
- Define a generator function that takes the input list, the word to remove, and the number of occurrences of the word to remove.
- Use a loop to iterate through each element of the input list.
- If the current element is not equal to the word to remove, yield it. Otherwise, decrement the counter and yield the element only if the counter is greater than zero.
- Use the generator function to create a new list with the desired elements.
- Return the new list.
Python3
def remove_word(list1, word, n1):
def generator():
count = 0
for i in list1:
if i ! = word or (i = = word and count ! = n1):
yield i
if i = = word:
count + = 1
return list (generator())
list1 = [ "he" , "is" , "ankit" , "is" , "raj" , "is" , "ankit raj" ]
word = "is"
n1 = 3
print ( "New list is :" , remove_word(list1, word, n1))
|
OUTPUT:
New list is : ['he', 'is', 'ankit', 'is', 'raj', 'is', 'ankit raj']
Time Complexity: O(n), where n is the length of the input list.
Auxiliary Space: O(1), since we only need to store a constant number of variables (the loop index, the counter, and the element) at any given time.
Approach #5: Using NumPy
In this approach, we will use the NumPy library to solve the problem. We can convert the given list to a NumPy array and then use NumPy’s delete function to remove the Nth occurrence of the given word.
Algorithm:
- Convert the given list to a NumPy array using the np.array() method.
- Find the indices of the Nth occurrence of the given word using the np.where() method.
- If the number of occurrences is less than N, print “Item not found” and return the original list.
- Otherwise, use the np.delete() method to remove the Nth occurrence of the given word from the NumPy array.
- Convert the modified NumPy array back to a list using the tolist() method and return it.
Python3
import numpy as np
def RemoveIthWord( list , word, N):
arr = np.array( list )
indices = np.where(arr = = word)[ 0 ]
if len (indices) < N:
print ( "Item not found" )
return list
arr = np.delete(arr, indices[N - 1 ])
new_list = arr.tolist()
print ( "Updated list is:" , new_list)
return new_list
list = [ "geeks" , "for" , "geeks" ]
word = "geeks"
N = 2
RemoveIthWord( list , word, N)
|
Output:
Updated list is: ['geeks', 'for']
Time Complexity:
The time complexity of this approach depends on the time complexity of the NumPy functions used. In our case, the time complexity of np.array(), np.where(), np.delete(), and tolist() methods are O(1), O(n), O(n), and O(n), respectively. Therefore, the overall time complexity of this approach is O(n).
Space Complexity:
The space complexity of this approach depends on the size of the NumPy array created. In our case, the space complexity is O(n) because we create a NumPy array of size n where n is the length of the input list.
Similar Reads
Python program to find the occurrence of substring in the string
Given a list of words, extract all the indices where those words occur in the string. Input : test_str = 'geeksforgeeks is best for geeks and cs', test_list = ["best", "geeks"] Output : [2, 4] Explanation : best and geeks occur at 2nd and 4th index respectively. Input : test_str = 'geeksforgeeks is
4 min read
Python program to find the longest word in a sentence
In this article, we will explore various methods to find the longest word in a sentence. Using LoopFirst split the sentence into words using split() and then uses a loop (for loop) to iterate through the words and keeps track of the longest word by comparing their lengths. [GFGTABS] Python s =
1 min read
Python Program to Find the Number of Unique Words in Text File
Given a text file, write a python program to find the number of unique words in the given text file in Python. Examples: Input: gfg.txtOutput: 18Contents of gfg.txt: GeeksforGeeks was created with a goal in mind to provide well written well thought and wellexplained solutions for selected questionsE
2 min read
Python - Remove first occurrence of K in Tuple
Sometimes, while working with Python tuples, we can have a problem in which we need to perform the removal of the first occurrence of an element in tuple. This type of problem can have applications in many domains such as school programming. Let's discuss certain ways in which this task can be perfo
7 min read
Python program to Remove the last element from list
Given a list of numbers or strings, the task is to write a Python program to remove the last element from a list. Example: Input : [12,53,11,76,22,21] Output : [12,53,11,76,22] Input : ["abc","gfg","text","python"] Output : ["abc","gfg","text"] The application of this type of problem in day-day prog
3 min read
Python - Count occurrences of each word in given text file
Many times it is required to count the occurrence of each word in a text file. To achieve so, we make use of a dictionary object that stores the word as the key and its count as the corresponding value. We iterate through each word in the file and add it to the dictionary with a count of 1. If the w
4 min read
Python program to remove last element from set
Given a set, the task is to write a Python program to delete the last element from the set. Example: Input: {1,2,3,4}Remove 4Output: {1,2,3} Input: {"Geeks","For"}Remove GeeksOutput: {"For"}Explanation: The idea is to remove the last element from the set 4 in the first case and "Geeks" in the second
2 min read
Python program to count words in a sentence
In this article, we will explore different methods for counting words in a sentence. The split() method is one of the simplest and most efficient ways to count words in a sentence. [GFGTABS] Python s = "Python is fun and versatile." # Counting words word_count = len(s.split()) print(word_c
2 min read
Python program to calculate the number of words and characters in the string
We are given a string we need to find the total number of words and total number of character in the given string. For Example we are given a string s = "Geeksforgeeks is best Computer Science Portal" we need to count the total words in the given string and the total characters in the given string.
3 min read
Python program to find the smallest word in a sentence
Given a string S of lowercase English alphabets, the task is to print the smallest word in the given string. Examples: Input: S = âsky is blueâOutput: "is"Explanation: Length of âskyâ is 3.Length of is âisâ 2.Length of âblueâ is 4.Therefore, the smallest word is âisâ. Input: S = âgeeks for geeksâOut
5 min read