Python: number of duplicate items in a list

I am new to Python. I am trying to find an easy way to count the number of items repeated in a list, for example.

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

Output:

 a: 3 b: 1 c: 3 
+8
python
source share
5 answers

You can do this with 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} 
+27
source share

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}) 
+6
source share

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} 
+3
source share
 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) 

Hooray!! Link

0
source share
 lst = ["a", "b", "a", "c", "c", "a", "c"] temp=set(lst) result={} for i in temp: result[i]=lst.count(i) print result 

Output:

 {'a': 3, 'c': 3, 'b': 1} 
0
source share

All Articles