Q:

Display all duplicate items from a list using python programming

0

Display all duplicate items from a list

Given:

sample_list = [10, 20, 60, 30, 20, 40, 30, 60, 70, 80]

Expected Output: -

[20, 60, 30]

All Answers

need an explanation for this answer? contact us directly to get an explanation for this answer

Hint:

  1. Use the counter() method of the collection module.
  2. 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)

need an explanation for this answer? contact us directly to get an explanation for this answer

total answers (1)

This question belongs to these collections

Similar questions


need a help?


find thousands of online teachers now