How to count the occurrences of an item in a list using Python
Using count()
Lists in python have a built-in function called count()
which accepts an element as a parameter, searches the list for the occurrences of this item and returns back the result as an integer. For example,
['a', 'b', 'c', 'a', 'a', 'c'].count('c')
# 2
The count()
function runs in a O(n) time. Therefore, if you want to find the occurrences of just one element then this function is suitable and is the most idiomatic in my opinion.
Using the collections.Counter
class
From the python documentation, a Counter
is a dict
subclass for counting hashable objects. The result is a dictionary of the list elements as keys and their counts and values. For example,
from collections import Counter
my_list = ['a', 'b', 'c', 'a', 'a', 'c']
Counter(my_list)
Counter({'a': 3, 'b': 1, 'c': 2})
The results of the Counter
class are stable meaning that the order of the list will be preserved. The Counter
class has O(n) complexity. Therefore, it's better to be used if you have to count the occurrences of more than one elements in a list.
Using a for loop
If you just want to practise python and you want to do this on your own you can do something similar to the code below:
my_list = ['a', 'b', 'c', 'a', 'a', 'c']
count = 0
search_element = 'c'
for element in my_list:
if element == search_element:
count += 1
count
# 2
In this example, we iterate through the list and every time we find the element we are searching for we increase the count
variable. The result will be in the count
variable in the end. I would recommend to avoid writing your own solution since built-in solutions exist. This way you avoid making trivial bugs that otherwise you would't make. Always rely on built-in functionality if it's available.
Other ways
There are other ways to do this as well using different libraries such as pandas and numpy. However, I will not be showing these examples here since it's outside of the scope of this tutorial.
Stack overflow answers
You can check the stack overflow answers here as well.
The end
Congratulations! You made it to the end.
If you like the content here, please consider subscribing. No spam ever!
If you have any comments or feedback feel free to reach me @costapiy