This tutorial will go through how to use Python to count how often different items appear in a given list.
You will learn how to do this using the count() list method, the naive implementation, the Counter() method from the collections library, values_count() from the pandas library, countOf() from the operator library and a dictionary comprehension.
Table of contents
Count Occurrences Using count()
The most efficient way to count the number of occurrences in a list is to use the built-in count() method. The count() method returns how many times a given object occurs in a list. Let’s look at an example:
def count_n(lst, n):
return lst.count(n)
In the above code, we define a function that takes a list and the element we want to count. The function calls the count() method and returns the count. Next, we will define a list of integers and the integer value we want to count in the list.
lst = [2, 2, 4, 3, 10, 20, 10, 8, 2, 8, 3, 10]
n = 10
count = count_n(lst, n)
print(f'The number {n} occurs {count} times in the list')
Let’s run the code to get the result:
The number 10 occurs 3 times in the list
If the value we specify does not exist in the list, the count() method will return 0.
count_n(lst, 11)
0
Count Occurrences Using Iteration
We can use a simple counter in a for loop to count a specific element as it appears in a list. Let’s look at an example:
def count_n(lst, n):
count = 0
for i in lst:
if i == n:
count += 1
return count
In the above code, we define a function that takes a list and the element value we want to count. The function defines a counter that starts at 0, and then it iterates over the elements in the list using a for loop. If the element in the list is equal to the specified value, the counter increases by 1. Once the for loop is complete, the function returns the count. Next, we will define a list of integers and the integer value we want to count in the list.
lst = [2, 2, 4, 3, 10, 20, 10, 8, 2]
n = 10
count = count_n(lst, n)
print(f'The number {n} occurs {count} times in the list')
Let’s run the code to get the result:
The number 10 occurs 2 times in the list
If the value we specify does not exist in the list, the function will return 0.
Count Occurrences Using Counter()
The Counter() method returns a dictionary with the occurrences of all elements as a key-value pair. The key is the element, and the value is the number of times the element occurred in the list. We can import the Counter() method from the collections module. Let’s look at an example:
from collections import Counter
lst = [2, 2, 4, 3, 10, 20, 10, 8, 2]
n = 2
count = Counter(lst)
print(f'The number {n} occurs {count[n]} times in the list')
In the above code, we call the Counter() method on a list of integers, which produces a Counter object. We can get the count for a specific value by passing a key to the count dictionary.
The number 2 occurs 3 times in the list
If we pass a key that does not exist in the Count, the Counter object returns the value of 0 as shown below:
from collections import Counter
lst = [2, 2, 4, 3, 10, 20, 10, 8, 2]
n = 2
count = Counter(lst)
print(count[1])
0
Count Occurrences Using Pandas
Pandas provides a way to count occurrences in a Pandas column, using the value_counts() method. For further reading on the basics of Pandas, go to the tutorial called: Introduction to Pandas: A Complete Tutorial for Beginners. To count the number of occurrences in a list, we need to load the list into a Pandas Series object. Let’s look at an example:
import pandas as pd
def count_n(lst, n):
counts = pd.Series(lst).value_counts()
print(counts)
return counts[n]
lst = [2, 2, 4, 3, 10, 20, 10, 8, 2, 8, 3, 10]
n = 8
count = count_n(lst, n)
print(f'The number {n} occurs {count} times in the list')
In the above code, we define a function that accepts a list and a value we want to count in the list. We create the Series object using pd.Series() and then use the value_counts() method to get a series containing the counts of each element value in the list. We can access the count of a specific value using .get() or square brackets. Let’s run the code to get the result:
The number 8 occurs 2 times in the list
Count Occurrences Using Operator
We can use the countOf() method from the operator library to count the occurrences of an element in a list. The countOf() method takes two arguments: the list to count the elements and the element value we want to count. Let’s look at an example:
from operator import countOf
lst =[2, 2, 4, 3, 10, 20, 10, 8, 2, 8, 3, 10]
n = 2
count = countOf(lst, n)
print(f'The number {n} occurs {count} times in the list')
Let’s run the code to get the output:
The number 2 occurs 3 times in the list
Count Occurrences Using Dictionary Comprehension
Dictionary comprehension lets us generate new dictionaries from items in an iterable object. We can use dictionary comprehension to create a dictionary that holds the occurrence counts of all the elements in a list. We can then access the count of a specific element value by passing a key to the dictionary. Let’s look at an example below:
def count_n(lst, n):
counts = {item:lst.count(item) for item in lst}
return counts.get(n)
lst = [2, 2, 4, 3, 10, 20, 10, 8, 2, 8, 3, 10]
n = 3
count = count_n(lst, n)
print(f'The number {n} occurs {count} times in the list')
In the above code, we define a function that uses a dictionary comprehension to loop over the elements in the list and assigns a key to each element. Dictionaries only allow for unique keys, so there will be no duplicate keys. The value is the count of each element in the list. The function uses get() to retrieve the count for the specified element. Let’s run the code to get the result:
The number 3 occurs 2 times in the list
Summary
Congratulations on reading to the end of this tutorial! The most efficient way to count the occurrences of an element in a list is to use the count() method.
For further reading on manipulation of lists, go to the articles:
- How to Calculate the Cartesian Product in Python.
- How to Remove Empty Strings from a List of Strings in Python
- How to Remove an Element from a List in Python
Go to the online courses page on Python to learn more about coding in Python for data science and machine learning.
Have fun and happy researching!
Suf is a senior advisor in data science with deep expertise in Natural Language Processing, Complex Networks, and Anomaly Detection. Formerly a postdoctoral research fellow, he applied advanced physics techniques to tackle real-world, data-heavy industry challenges. Before that, he was a particle physicist at the ATLAS Experiment of the Large Hadron Collider. Now, he’s focused on bringing more fun and curiosity to the world of science and research online.