I am new to python and I am just trying to get a count of duplicate elements. My code looks something like this:
n=int(input("Enter the number of products to be stored in a list : "))
list1=[]
for i in range(n):
items=int(input("value for product " + str(i+1) + " : "))
list1.append(items)
dup=[]
for a in list1:
if list1.count(a)>1:
dup.append(a)
print("Count of duplicate elements in the list: ",dup)
Output:
Enter the number of products in a list : 5
value for product 1 : 4
value for product 2 : 4
value for product 3 : 4
value for product 4 : 1
value for product 5 : 5
Count of duplicate elements in the list: [4, 4, 4]
The answer should be 1 because it is just the number 4 that is a duplicate value but I get the above output. Can someone please advice?
len(set(dup))in place ofdupin your last print.1when you're literallyprinting the contents of a list? When wouldprinting the contents of any list ever result in a single integer? Have you given it a try in modifying your logic to only add elements todupif they aren't already present there? If you break down the issue you're seeing here into smaller requirements, they are all questions that have been asked here many times before. Can you include a summary of what research you've done, with an explanation as to why that falls short for your requirements? How to Ask