How do I remove the second occurrence from a list in Python?

Python program to remove Nth occurrence of the given word

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" "?"]

Recommended: Please try your approach on {IDE} first, before moving on to the solution.


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 program to remove Nth
# occurrence of the given word
# Function to remove Ith word
def RemoveIthWord(lst, word, N):
newList = []
count = 0
# iterate the elements
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
# Driver code
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 program to remove Nth
# occurrence of the given word
# Function to remove Ith word
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
# Driver code
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 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 we need an index ? because pop( ) needs index to pass inside i.e pop(index).




# Python3 program to remove Nth
# occurrence of the given word
# Function to remove nth word
def omit(list1,word,n1):
# for counting the occurrence of word
count=0
# for counting the index number
# where we are at present
index=0
for i in list1:
index+=1
if i==word:
count+=1
if count==n1:
# (index-1) because in list
# indexing start from 0th position
list1.pop(index-1)
return list1
# Driver code
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']

Attention geek! Strengthen your foundations with the Python Programming Foundation Course and learn the basics.

To begin with, your interview preparations Enhance your Data Structures concepts with the Python DS Course. And to begin with your Machine Learning Journey, join the Machine Learning - Basic Level Course




Article Tags :
Python
Python Programs
Python list-programs

Introduction

In this section of python programming, we will understand the code to eliminate the nth occurrence of the given element from the list.

How do I remove the second occurrence from a list in Python?
on Oct 13 2021 Comment
0
Add a Grepper Answer

  • string remove last 3 characters python
  • python split only last occurrence of a character
  • numpy reg ex delete words before a specific character
  • strip first occurence of substring python
  • Python program to remove duplicate characters of a given string.
  • python remove last 4 characters from string
  • python remove multiple characters from string
  • drop all characters after a character in python
  • remove occurence of character from string python
  • how to remove first few characters from string in python
  • python string cut last n characters
  • how to remove every other letter from a string python
  • python find second occurrence in string
  • python remove characters from end of string
  • How to remove all characters after a specific character in python?
  • split at the second occurrence of the element python
  • removing odd index character of a given string in python
  • Python Remove all occurrences of a character from a string
  • python replace nth occurrence in string
  • python cut string after character

  • how to remove every second character from a string in python
  • python string remove characters after second symbol
  • python remove second occurrence of string in string
  • python remove second letter from string
  • python remove second occurrence of character in string
  • python remove second occurence of string
  • python remove nth occurrence of string in string
  • remove after nth occurrence python
  • python remove everything after second occurrence of character
  • python remove second occurrence of sring in string
  • strip string python on secin occurrence

Python program to remove nth occurrence of the given word list

  • To allow the user to input a number of elements in the list and store it in a variable.
  • Accept the values into the list using a for loop and insert them into the python list.
  • Use a for loop to traverse through the elements in the list.
  • Then use an if statement to check if the word to be removed matches the element and the occurrence number and otherwise, it appends the element to another list.
  • The number of repetitions along with the updated list and distinct elements is printed.
# python program to remove nth occurrence of the given word a=[] n= int(input("Enter the number of elements in list:")) for x in range(0,n): element=input("Enter element" + str(x+1) + ":") a.append(element) print(a) c=[] count=0 b=input("Enter word to remove: ") n=int(input("Enter the occurrence to remove: ")) for i in a: if(i==b): count=count+1 if(count!=n): c.append(i) else: c.append(i) if(count==0): print("Item not found ") else: print("The number of repetitions is: ",count) print("Updated list is: ",c) print("The distinct elements are: ",set(a))

After executing the program, the output will be:

Enter the number of elements in list: 5 Enter element1: test Enter element2: test Enter element3: my Enter element4: world Enter element5: world ['test', 'test', 'my', 'world', 'world'] Enter word to remove: world Enter the occurrence to remove: 4 The number of repetitions is: 2 Updated list is: ['test', 'test', 'my', 'world', 'world'] The distinct elements are: {'test', 'world', 'my'}

1. Using list.remove() function

list.remove(x) removes the first occurrence of value x from the list, but it fails to remove all occurrences of value x from the list.

1
2
3
4
5
6
7
if __name__ == '__main__':
l = [0, 1, 0, 0, 1, 0, 1, 1]
val = 0
l.remove(val)
print(l)# prints [1, 0, 0, 1, 0, 1, 1]

DownloadRun Code


To remove all occurrences of an item from a list using list.remove(), you can take advantage of the fact that it raises a ValueError when it can’t find the specified item in the list. The idea is to repeatedly call remove() function until it raises a ValueError exception. This is demonstrated below:

1
2
3
4
5
6
7
8
9
10
11
12
13
if __name__ == '__main__':
l = [0, 1, 0, 0, 1, 0, 1, 1]
val = 0
try:
while True:
l.remove(val)
except ValueError:
pass
print(l)# prints [1, 1, 1, 1]

DownloadRun Code