Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a pythonic way of counting the occurrences of each element in an array?

Just like the title suggests, I just wanted to know whether there is a pythonic way of counting the occurrence of each element in an array. I have implemented the code below:

my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']

occurrences = {}
for item in my_array:
    try:
        occurrences[item] += 1
    except KeyError:
        occurrences[item] = 1

And it gives me the ff result:

dog: 2
cat: 3
rabbit: 2
elephant: 2
bee: 1

Is there a more pythonic way of doing this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

PS: Sorry if this question is kind of stupid. I might delete this if someone agrees.

PPS: If this question is duplicated, can u drop the link and I’ll give it a go. 🙂

>Solution :

Counter from the collections module in the standard library is what you are looking for.
https://docs.python.org/3/library/collections.html#collections.Counter

Used like so:

from collections import Counter

my_array = ['dog', 'cat', 'rabbit', 'rabbit', 'elephant', 'bee', 'dog', 'cat', 'cat', 'elephant']
c = Counter(my_array)

C then returns
Counter({'cat': 3, 'dog': 2, 'rabbit': 2, 'elephant': 2, 'bee': 1})

You can also convert this to a dictionary of elements: counts.
dict(c)

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading