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:
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.
16. Write a program to count total number of duplicate elements from below array Ex: [22, 15, 63, 45, 15, 81, 22, 12]
solve this code
from collections import Counter
MyList =[22, 15, 63, 45, 15, 81, 22, 12]
res = Counter(MyList)
print(res)