Skip to content

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 basic 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

Using a dictionary to count occurrences

my_list = ['a', 'b', 'c', 'a', 'd', 'e', 'b', 'a']
count_dict = {}

# loop through the list and count occurrences of each element
for element in my_list:
    if element in count_dict:
        count_dict[element] += 1
    else:
        count_dict[element] = 1

# print the results
for element, count in count_dict.items():
    if count > 1:
        print(f"{element} appears {count} times in the list.")

In this method, we use a dictionary to count the occurrences of each element in the list. We loop through the list and add each element as a key in the dictionary. If the key already exists, we increment its value. Finally, we loop through the dictionary and print the elements that have a count greater than 1.

Comment if you have any doubts or suggestions on this Python list topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

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

2 thoughts on “Python find duplicates in a list and count them | Example code”

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading