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
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}
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
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})
This can also be used to get a count for a single element
>>> from collections import Counter
>>> c = Counter(l)
>>> c['a']
5
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
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
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
Free illustrations resources for the web - Make your next project cooler!😎
Kedar Kodgire ・ Jan 2 '20
Three dots "..." in JS - Spread and Rest explained
Kedar Kodgire ・ Mar 25 '20
Stuck at home, corona? Spend your time learning for free (15,000+ hours content).
Kedar Kodgire ・ Mar 27 '20
Don't forget to follow me on Twitter or Dev for updates on amazing technology stuff.
Top comments (2)
The
for ... in ...
loop is not necessarily the fastest, or at least not anymore. According to this benchmarkCounter
was the slowest in python2, but was optimized in python3 to be significantly faster.Ohh, didn't knew this before. Thanks for sharing..