This article is created to cover some programs in Python that find and removes all the duplicate elements or items from the given list. Here are the list of programs covered in this article:
The question is, write a Python program that removes all duplicates from given list. The program given below is answer to this question:
print("Enter 10 elements for the list: ") mylist =  for i in range(10): mylist.append(input()) newlist =  for i in range(10): if mylist[i] not in newlist: newlist.append(mylist[i]) print("\nThe new list is: ") print(newlist)
Here is its sample run:
Now supply the input as any 10 elements including some duplicates say 1, 2, 3, 4, 5, 4, 3, 2, 1, 2 and
ENTER key to remove all duplicates and print new list without any duplicate items like shown in the sample output given below:
This is the modified version of previous program. In this program, users are allowed to define the size of list along with its items. This program also prints message according to the availability of duplicates in the list. Like what if no duplicate item found, only 1 or more than 1 duplicates found in the list.
mylist = list() print("Enter the size of list: ", end="") tot = int(input()) print("Enter", tot, "elements for the list: ", end="") for i in range(tot): mylist.append(input()) newlist =  count = 0 for i in range(tot): if mylist[i] not in newlist: newlist.append(mylist[i]) else: count = count+1 if count==0: print("\nNo duplicate element found!") elif count==1: print("\nOnly 1 duplicate element found and removed successfully!") print("\nNow the new list is:", newlist) else: print("\nAll", count, "duplicate elements found and removed successfully!") print("\nNow the new list is:", newlist)
Here is its sample run with user input, 5 as size and 1, 2, 1, 3, 2 as five elements:
© Copyright 2021. All Rights Reserved.