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 remove K length words in String
Given a String, write a Python program to remove all the words with K length. Examples: Input : test_str = 'Gfg is best for all geeks', K = 3 Output : is best geeks Explanation : Gfg, for and all are of length 3, hence removed. Input : test_str = 'Gfg is best for all geeks', K = 2 Output : Gfg best
5 min read
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 remove each y occurrence before x in List
Given a list, remove all the occurrence of y before element x in list. Input : test_list = [4, 5, 7, 4, 6, 7, 4, 9, 1, 4], x, y = 6, 4 Output : [5, 7, 6, 7, 4, 9, 1, 4] Explanation : All occurrence of 4 before 6 are removed. Input : test_list = [4, 5, 7, 4, 6, 7, 4, 9, 1, 4], x, y = 6, 7 Output : [4
5 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 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 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
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 | Ways to find nth occurrence of substring in a string
Given a string and a substring, write a Python program to find the nth occurrence of the string. Let's discuss a few methods to solve the given task. Get Nth occurrence of a substring in a String using regex Here, we find the index of the 'ab' character in the 4th position using the regex re.findite
4 min read
Python Program to Return the Length of the Longest Word from the List of Words
When working with lists of words in Python, we may need to determine the length of the longest word in the list. For example, given a list like ["Python", "with", "GFG], we would want to find that "Python" has the longest length. Let's go through some methods to achieve this. Using max() max() funct
3 min read
Python - Non-Overlapping occurrences of N Repeated K character
Given a String, compute non-overlapping occurrences of N repeated K character. Input : test_str = 'aaabaaaabbaa', K = "a", N = 3 Output : 2 Explanation : "aaa" occurs twice as non-overlapping run. Input : test_str = 'aaabaaaabbbaa', K = "b", N = 3 Output : 1 Explanation : "bbb" occurs once as non-ov
6 min read