How to Remove the ith Duplicate List Element in Python


In this example we will show how to delete the ith duplicate element of a list in Python.

Source Code

#! /usr/bin/env python3
# -*- coding: utf-8 -*-

def userList():
    n = int(input("Please input the number of elements in the list: "))
    a = []
    for i in range(n):
        j = input("Please input the " + str(i + 1) + "th element: ")
        a.append(j)
    return a

a = userList()
print("Original list: ", a)
b = []
count = 0
el_remove =input("Please input the element to delete: ")
n = int(input("Please input the index of duplicated element: "))
for i in a:
    if i == el_remove:
        count = count + 1
        if count != n:
            b.append(i)
    else:
        b.append(i)
if count == 0:
    print("The element does not exist.")
else:
    print("The element {} to be deleted is {}th elment".format(el_remove, count - 1))
    print("After deleting: ", b)

Output:

Case 1:
Please input the number of elements in the list: 6
Please input the 1th element: Green
Please input the 2th element: Green
Please input the 3th element: Red
Please input the 4th element: Blue
Please input the 5th element: Blue
Please input the 6th element: Green
Original list: ['Green', 'Green', 'Red', 'Blue', 'Blue', 'Green']
Please input the element to delete: Green
Please input the index of duplicated element: 2
The element Green  to be deleted is 2th element.
After deleting: ['Green', 'Red', 'Blue', 'Blue', 'Green']

Case 2:
Please input the number of elements in the list: 4
Please input the 1th element: Green
Please input the 2th element: Red
Please input the 3th element: Blue
Please input the 4th element: Green
Original list: ['Green', 'Red', 'Blue', 'Green']
Please input the element to delete: Purple
Please input the index of duplicated element: 2
The element does not exist.
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments