Python: count repeated elements in the list

PythonPython 2.7

Python Problem Overview


I am new to Python. I am trying to find a simple way of getting a count of the number of elements repeated in a list e.g.

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

Output:

a: 3
b: 1
c: 3

Python Solutions


Solution 1 - Python

You can do that using count:

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

>>> print my_dict     #or print(my_dict) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

Or using collections.Counter:

from collections import Counter

a = dict(Counter(MyList))

>>> print a           #or print(a) in python-3.x
{'a': 3, 'c': 3, 'b': 1}

Solution 2 - Python

Use Counter

>>> from collections import Counter
>>> MyList = ["a", "b", "a", "c", "c", "a", "c"]
>>> c = Counter(MyList)
>>> c
Counter({'a': 3, 'c': 3, 'b': 1})

Solution 3 - Python

This works for Python 2.6.6

a = ["a", "b", "a"]
result = dict((i, a.count(i)) for i in a)
print result

prints

{'a': 2, 'b': 1}

Solution 4 - Python

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

>expected outputs {a: 3, b: 1,c:3}

duplicateFrequencies = {}
for i in set(yourList):
    duplicateFrequencies[i] = yourList.count(i)

Cheers!! Reference

Solution 5 - Python

In [2]: MyList = ["a", "b", "a", "c", "c", "a", "c"]

In [3]: count = {}

In [4]: for i in MyList:
   ...:     if not i in count:
   ...:         count[i] = 1
   ...:     else:
   ...:         count[i] +=1
   ...:

In [5]: count
Out[5]: {'a': 3, 'b': 1, 'c': 3}

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJojoView Question on Stackoverflow
Solution 1 - Pythonsshashank124View Answer on Stackoverflow
Solution 2 - PythonJayanth KoushikView Answer on Stackoverflow
Solution 3 - PythonPeter KellyView Answer on Stackoverflow
Solution 4 - PythonDaniel AdenewView Answer on Stackoverflow
Solution 5 - PythonNishant NawarkhedeView Answer on Stackoverflow