Program to remove the nth occurrence of element using Python

Introduction

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

Program to remove the nth occurrence of element using Python

Program

def del_word(list,element,count):
    n = 0
    for i in range(0,len(list)):
        if list[i] == element:
            n = n+ 1
# Check for nth occurence and del if found
            if n == count:
                del(list[i])
                return list
               
list = ['is', 'at', 'is', 'is']
element = 'is'
count = 1
print(del_word(list,element,count))

Output

Program to remove the nth occurrence of element using Python Output

Explanation

In the above python code, we have created a list with few elements, a variable element which stores the string value to be eliminated and a variable count which stores the occurrence value. Here the function del_word will locate the word in the list and each time the element is found the counter variable n will increase by one and is checked against the variable count. If the counter variable gets equals to the occurrence given, the word is deleted from the list and the new list is returned.

In the code, we want to delete the first occurrence of ‘is’. So the very time ‘is’ is encountered it is being deleted from the list and output is returned.

Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.