Skip to content

Count repeated elements in list Python

  • by

You can do that using count or collection Counter to Count repeated elements in a list Python. Each count the call goes over the entire list of n elements. Calling count in a loop n times means n * n total checks.

Count repeated elements in the list of Python

A simple example code gets a count of the number of elements repeated in a list.

from collections import Counter

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

# count
my_dict = {i: MyList.count(i) for i in MyList}
print(my_dict)

# counter
res = Counter(MyList)
print(res)

Output:

Count repeated elements in the list of Python

Much faster-using pandas: pd.DataFrame(MyList, columns=["x"]).groupby('x').size().to_dict()

if you use a ‘set’ for get unique values in the ‘for’ it will go faster: setList = list(set(Mylist)) my_dict = {i:MyList.count(i) for i in setList}

Do 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.

Leave a Reply

Your email address will not be published. Required fields are marked *