88

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
0

5 Answers 5

204

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}
10
  • first option result in syntax error Apr 23, 2014 at 10:16
  • 2
    It raises a Syntax Error in Python 3 (print is a function), it works in 2.7. Apr 23, 2014 at 10:19
  • @sshashank124 ran it against 2.6.6, should have said that sorry - nevermind! Apr 23, 2014 at 10:21
  • 4
    This solution is super slow. Much faster using pandas: pd.DataFrame(MyList, columns=["x"]).groupby('x').size().to_dict()
    – Make42
    Jul 10, 2017 at 15:19
  • 3
    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} Jun 7, 2021 at 14:45
26

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})
11

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}
1
  • 1
    +1 for compatibility with older versions. Apr 23, 2014 at 10:22
7
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

0
7
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}

Not the answer you're looking for? Browse other questions tagged or ask your own question.