IOT RnD
IOT RnD

Reputation: 9

How to find the duplicates in a list and create another list with them ? with answer

My own Solution:

list1=[1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
counter=0
for j in list(set(list1)):
    for i in list1:
        if j==i:
            counter=counter+1
    print(j,"have",counter,"duplicates")
    counter=0

give some suggestion

Upvotes: 1

Views: 65

Answers (1)

Samwise
Samwise

Reputation: 71542

Using collections.Counter:

>>> list1 = [1,2,3,4,4,5,5,5,6,6,7,8,8,8,8]
>>> from collections import Counter
>>> [(i, count) for i, count in Counter(list1).items() if count > 1]
[(4, 2), (5, 3), (6, 2), (8, 4)]

Upvotes: 1

Related Questions