Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: count repeated elements in the list [duplicate]

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 
like image 644
Jojo Avatar asked Apr 23 '14 10:04

Jojo


People also ask

How do you count the number of repeated items in a list Python?

Operator. countOf() is used for counting the number of occurrences of b in a. It counts the number of occurrences of value. It returns the Count of a number of occurrences of value.

How do you count duplicate elements in a list?

from collections import Counter MyList = ["a", "b", "a", "c", "c", "a", "c"] duplicate_dict = Counter(MyList) print(duplicate_dict)#to get occurence of each of the element. print(duplicate_dict['a'])# to get occurence of specific element. remember to import the Counter if you are using Method otherwise you get error.


2 Answers

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} 
like image 200
sshashank124 Avatar answered Sep 18 '22 21:09

sshashank124


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}) 
like image 20
Jayanth Koushik Avatar answered Sep 18 '22 21:09

Jayanth Koushik