by BehindJava
Write a program to Remove the Duplicate Items from a List in Python
In this tutorial we are going to learn about removing the Duplicate Items from a List in Python.
Python Program to Remove the Duplicate Items from a List
a=[]
n= int(input("Enter the number of elements in list:"))
for x in range(0,n):
element=int(input("Enter element" + str(x+1) + ":"))
a.append(element)
b = set()
unique = []
for x in a:
if x not in b:
unique.append(x)
b.add(x)
print("Non-duplicate items:")
print(unique)
Explanation
- User must enter the number of elements in the list and store it in a variable.
- User must enter the values of elements into the list.
- The append function obtains each element from the user and adds the same to the end of the list as many times as the number of elements taken.
- The for loop basically traverses through the elements of the list and the if statement checks if the element is a duplicate or not.
- If the element isn’t a duplicate, it is added into another list.
- The list containing non-duplicate items is then displayed.