Ways to count occurrences of the list items in Python
Kedar Kodgire

Kedar Kodgire @kedark

About: Lead Data Engineer with 3+ years of comprehensive experience in Google Cloud Platform with an in-depth understanding of large-scale data, data warehouses, data modeling, data pipelines, and data strea

Location:
Canada
Joined:
Oct 10, 2018

Ways to count occurrences of the list items in Python

Publish Date: Aug 2 '20
17 2

Table Of Contents

Introduction

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.

Count

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')
5
>>> l.count('e')
1
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

operator

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')
5
Enter fullscreen mode Exit fullscreen mode

let's go to the next method

Counter

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})
Enter fullscreen mode Exit fullscreen mode

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

>>> from collections import Counter

>>> c = Counter(l)

>>> c['a']
5
Enter fullscreen mode Exit fullscreen mode

Pandas

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
Enter fullscreen mode Exit fullscreen mode

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']
5
Enter fullscreen mode Exit fullscreen mode

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}
Enter fullscreen mode Exit fullscreen mode

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.

Comments 2 total

  • Jing Xue
    Jing XueAug 3, 2020

    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.

    • Kedar Kodgire
      Kedar KodgireAug 3, 2020

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

Add comment