Advertisements
Advertisements
Question
Write a program to read a list of elements. Modify this list so that it does not contain any duplicate elements, i.e., all elements occurring multiple times in the list should appear only once.
Answer in Brief
Solution
Program:
#function to remove the duplicate elements
def removeDup(list1):
#Checking the length of list for 'for' loop
length = len(list1)
#Defining a new list for adding unique elements
newList = []
for a in range(length):
#Checking if an element is not in the new List
#This will reject duplicate values
if list1[a] not in newList:
newList.append(list1[a])
return newList
#Defining empty list
list1 = []
#Asking for number of elements to be added in the list
inp = int(input("How many elements do you want to add in the list? "))
#Taking the input from user
for i in range(inp):
a = int(input("Enter the elements: "))
list1.append(a)
#Printing the list
print("The list entered is:",list1)
#Printing the list without any duplicate elements
print("The list without any duplicate element is:",removeDup(list1))
OUTPUT:
How many elements do you want to add in the list? 6
Enter the elements: 1
Enter the elements: 1
Enter the elements: 2
Enter the elements: 2
Enter the elements: 3
Enter the elements: 4
The list entered is: [1, 1, 2, 2, 3, 4]
The list without any duplicate element is: [1, 2, 3, 4]
shaalaa.com
Traversing a List
Is there an error in this question or solution?