How to count duplicate elements in Python list?

Following Python program calculates duplicate elements in Python list.

Method 1: Without Using Any Library


lst = ["a", "b", "c", "d", "e", "f", "g", "a", "b", "c", "a"]

dct = {}

for i in lst:
    dct[i]=lst.count(i)
    
print(dct)

Output

{'a': 3, 'b': 2, 'c': 2, 'd': 1, 'e': 1, 'f': 1, 'g': 1}

Similary, we can use dictionary comprehension as:


lst = ["a", "b", "c", "d", "e", "f", "g", "a", "b", "c", "a"]

dct = {i:lst.count(i) for i in lst}

print(dct)

Output

{'a': 3, 'b': 2, 'c': 2, 'd': 1, 'e': 1, 'f': 1, 'g': 1}

Method 2: Using collections.Counter


from collections import Counter

lst = ["a", "b", "c", "d", "e", "f", "g", "a", "b", "c", "a"]

dct = Counter(lst)

print(dct)

Output

Counter({'a': 3, 'b': 2, 'c': 2, 'd': 1, 'e': 1, 'f': 1, 'g': 1})