Write a Python program to remove duplicates from a list
This program is a Python script that takes a list of integers as input, and it then uses a set to remove duplicates and print out the unique values.
- It starts by initializing an empty set called "dup" and an empty list called "uniq". Then it uses a for loop to iterate through the list "a". For each element, it checks if it is already in the set "dup" using the "in" keyword. If the element is not in the set, it means it is a unique value and it will append it to the "uniq" list, and also add it to the "dup" set.
- At the end, it prints out the set "dup" which contains all the unique elements of the list "a". The commented out lines are an alternative way of achieving the same outcome using the built-in python function "set()" which will convert any iterable into a set, removing all duplicates.
Source Code
a = [1,2,3,7,2,1,5,6,4,8,5,4]
"""
b=set(a)
print(b)
"""
dup = set()
uniq = []
for x in a:
if x not in dup:
uniq.append(x)
dup.add(x)
print(dup)
Output
{1,2,3,4,5,6,7,8}