Count Duplicate Values in a List | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Count Duplicate Values in a List

"Write a function named count_duplicates that accepts a list of integers as a parameter and that returns the number of duplicate values in the list. A duplicate value is a value that also occurs earlier in the list. For example, if a list named a contains [1, 4, 2, 4, 7, 1, 1, 9, 2, 3, 4, 1], then the call of count_duplicates(a) should return 6 because there are three duplicates of the value 1, one duplicate of the value 2, and two duplicates of the value 4. Constraints: The list could be empty or could contain only a single element in such cases, your function should return 0. Do not modify the contents of the list." This is what I have... def count_duplicates(a): count = 0 for i in range(1, len(a), 1): first = str(a[i]) second = str(a[i + 1]) if first == second: count += 1 return count however I keep getting an "IndexError: list index out of range" after the "second = str(a[i + 1])" function. Any ideas how to fix this?

28th Mar 2018, 3:57 PM
Taylor Deal
Taylor Deal - avatar
2 Answers
+ 2
""" Rather than fixing your code (which have also logical mistake: you only compare contiguous items in the list), I will suggest another way to reach your goal: """ def count_duplicates(a): return len(a) - len(set(a))
28th Mar 2018, 4:24 PM
visph
visph - avatar
0
i suggest 2* for loops, the first take each element in the list and the other for loop compare it with each element in the list
4th Oct 2018, 8:04 PM
Mohammed Adel
Mohammed Adel - avatar