Python find duplicates in a list and count them | Example code

If you want to count duplicates for a given element then use the count() function. Use a counter() function or basics logic combination to find all duplicated elements in a list and count them in Python.

Example find duplicates in a list and count them in Python

Simple example code.

Using count()

Get the occurrence of a given element in the List. Count “b” in the list.

MyList = ["b", "a", "a", "c", "b", "a", "c", 'a']

res = MyList.count('b')

print(res)

Output: 2

And if want to count each of the elements in the List using for loop.

MyList = ["b", "a", "a", "c", "b", "a", "c", 'a']
res = {}

for i in MyList:
    res[i] = MyList.count(i)
    
print(res)

Output:

Python find duplicates in a list and count them

Same code using list comprehension

MyList = ["b", "a", "a", "c", "b", "a", "c", 'a']
res = {i:MyList.count(i) for i in MyList}

print(res)

Using collections.Counter()

You need to import Counter from the collection.

from collections import Counter

MyList = ["a", "b", "a", "c", "c", "a", "c"]
res = Counter(MyList)

print(res)
print(res['a'])

Output:

Counter({‘a’: 3, ‘c’: 3, ‘b’: 1})
3

Do comment if you have any doubts and suggestions on this Python list topic.

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.