DEV Community

Cover image for Ways to count occurrences of the list items in Python

Posted on

Count Occurrences in List Python Ways to count occurrences of the list items in Python

Table Of Contents


Hey guys,
hope you all are doing well during this crisis. I have been coding in python for a while and came across a situation where I had to count some occurrences for a particular element in the list and I came across a few cool techniques to do this. So, let's get started.


well, this is the most interesting and easy method to use, let's look at an example

>>> l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']
>>> l.count('a')
>>> l.count('e')

we can also use this method to get a count of all distinct values at once.

>>> l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']

>>> [[x,l.count(x)] for x in set(l)]
[['d', 2], ['b', 4], ['c', 3], ['e', 1], ['a', 5]]

>>> dict((x,l.count(x)) for x in set(l))
{'d': 2, 'b': 4, 'c': 3, 'e': 1, 'a': 5}


In this method, you have to import the operator module. Let's have a quick example

>>> l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']

>>> import operator as op

>>> op.countOf(l,'a')

let's go to the next method


Here you have to import Counter from the collections module.

>>> l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']

>>> from collections import Counter

>>> Counter(l)
Counter({'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1})

This can also be used to get a count for a single element

>>> from collections import Counter

>>> c = Counter(l)

>>> c['a']


pandas is a very popular library and it can also be used for this purpose

>>> import pandas as pd

>>> l = ['a', 'a', 'a', 'a', 'a', 'b', 'b', 'b', 'b', 'c', 'c', 'c', 'd', 'd', 'e']

>>> my_count = pd.Series(l).value_counts()

>>> my_count
a    5
b    4
c    3
d    2
e    1
dtype: int64

in case if you are looking for a count of a particular element

# you should run steps in the previous snippet before running this i.e. importing pandas, etc
>>> my_count['a']

loop & Dict

This is the fastest way among all the above, let's go to an example

>>> def countElement(a):
...     g = {}
...     for i in a:
...         if i in g:
...             g[i] +=1
...         else:
...             g[i] =1
...     return g
>>> countElement(l)
{'a': 5, 'b': 4, 'c': 3, 'd': 2, 'e': 1}

Well, this is it for the post. Hope you enjoyed it and it was helpful to you in some way.

Have a great day,
Happy Learning.

Other Reads

Don't forget to follow me on Twitter or Dev for updates on amazing technology stuff.

Top comments (2)

jingxue profile image
Jing Xue • Edited

The for ... in ... loop is not necessarily the fastest, or at least not anymore. According to this benchmark Counter was the slowest in python2, but was optimized in python3 to be significantly faster.

kedark profile image

Ohh, didn't knew this before. Thanks for sharing..