How to Remove Duplicate Items from a List in Python


In this example, we can learn about how to delete duplicates from the list in Python.

Source Code

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

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

a = userList()
print("The original list: ", a)
unique = []
for x in a:
    if x not in unique:
        unique.append(x)
print("After deleting: ", unique)

Output:

Please input the number of elements:  6
Please input the 1th element: 1
Please input the 2th element: 2
Please input the 3th element: 3
Please input the 4th element: 5
Please input the 5th element: 1
Please input the 6th element: 2
The original list: [1, 2, 3, 5, 1, 2]
After deleting: [1, 2, 3, 5]
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments