Use the counter() method of the collection module.
Create a dictionary that will maintain the count of each item of a list. Next, Fetch all keys whose value is greater than 2
Solution1:Using collections.Counter()
import collections
sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]
duplicates = []
for item, count in collections.Counter(sample_list).items():
if count > 1:
duplicates.append(item)
print(duplicates)
Solution2:
sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]
exist = {}
duplicates = []
for x in sample_list:
if x not in exist:
exist[x] = 1
else:
duplicates.append(x)
print(duplicates)
Hint:
counter()
method of the collection module.Solution1:Using
collections.Counter()
Solution2:
need an explanation for this answer? contact us directly to get an explanation for this answer