Skip to content

Python: Count Number of Occurrences in List (6 Ways)

Python Count Number of Occurrences in List Cover Image

In this tutorial, you’ll learn how use Python to count the number of occurrences in a list, meaning how often different items appear in a given list. You’ll learn how to do this using a naive implementation, the Python .count() list method, the Counter library, the pandas library, and a dictionary comprehension.

Being able to work with and manipulate lists is an important skill for anyone learning Python. Python lists are such common data structures that being able to count items in the lists can help you better understand how to work with lists.

The Quick Answer: Use .count() to Count Number of Occurrences in a Python List

Quick Answer - Python Count Number of Occurrences in a List
How to count the number of times an item occurs in a Python list

Use .count() to Count Number of Occurrences in a Python List

The easiest way to count the number of occurrences in a Python list of a given item is to use the Python .count() method. The method is applied to a given list and takes a single argument. The argument passed into the method is counted and the number of occurrences of that item in the list is returned.

Let’s see how we can use the .count() method to count the number of occurrences in a Python list:

# Count the Number of Occurrences in a Python list using .count()
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

count_a = items.count('a')
print(f'{count_a=}')

# Returns: count_a=3

We can see here that when we apply the .count() method to a list and pass in the item that we want to count, that the number of occurrences are returned.

Let’s see what would happen if we pass in an item that does not exist in the list:

# Count the Number of Occurrences in a Python list using .count()
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

count_f = items.count('f')
print(f'{count_f=}')

# Returns: count_f=0

When an item doesn’t exist in a list and the .count() method is applied, the value of 0 is returned.

This method is a very Pythonic way to get the number of occurrences in a Python list for a single item. However, if you wanted to count the number occurrences of more than one item in a list, it’d be much better to use a different method, such as the Counter library.

This is exactly what you’ll learn in the next section!

Need to automate renaming files? Check out this in-depth guide on using pathlib to rename files. More of a visual learner, the entire tutorial is also available as a video in the post!

Use Counter to Count Number of Occurrences in a Python List

Python comes built-in with a library called collections, which has a Counter class. The Counter class is used to, well, count items.

Let’s see how we can use the Counter class to count the number of occurrences of items in a Python list:

# Count the Number of Occurrences in a Python list using Counter
from collections import Counter
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

counts = Counter(items)
print(counts['a'])

# Returns: 3

The way that we can use the Counter class is to pass a list into the class. This creates a Counter object, where can access the counts for any item in the list.

Similar to the .count() method, if we pass in an item that doesn’t exist in a list, the value 0 is returned, as shown below:

# Count the Number of Occurrences in a Python list using Counter
from collections import Counter
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

counts = Counter(items)
print(counts['f'])

# Returns: 0

In the next section, you’ll learn how to use Pandas to count the number of occurrences in a list.

Want to learn more about Python list comprehensions? Check out this in-depth tutorial that covers off everything you need to know, with hands-on examples. More of a visual learner, check out my YouTube tutorial here.

Use Pandas to Count Number of Occurrences in a Python List

Pandas provides a helpful to count occurrences in a Pandas column, using the value_counts() method. I cover this method off in great detail in this tutorial – if you want to know the inner workings of the method, check it out.

In order to use Pandas to count the number of occurrences of a particular item, we’ll load the list in as a Pandas series object. These objects are indexable, meaning we can access items by their labelled index.

Let’s see how we can do this using Pandas:

# Count the Number of Occurrences in a Python list using Pandas
import pandas as pd
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

counts = pd.Series(items).value_counts()
print(counts.get('a'))

# Returns: 3

We first create a Pandas series by passing in the list and then use the .value_counts() method on the series. We can then access items the items using either list indexing using [] square brackets, our using the .get() method. The get method is much safer, as it will not crash if an item doesn’t exist. Want to learn more? Check out my article on accessing items safely in dictionaries in this tutorial.

In the next section, you’ll learn how to use operator to count the number of occurrences of an item in a Python list.

Want to learn more about calculating the square root in Python? Check out my tutorial here, which will teach you different ways of calculating the square root, both without Python functions and with the help of functions.

Use Operator to Count Number of Occurrences in a Python List

In this section, you’ll learn how to use the operator library to count the number of times an item appears in a list. The library comes with a helpful function, countOf(), which takes two arguments:

  1. The list to use to count items, and
  2. The item to count

Let’s see how we can use the method to count the number of times an item appears in a list:

# Count the Number of Occurrences in a Python list using operator
from operator import countOf
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']

count_a = countOf(items, 'a')
print(count_a)

# Returns: 3

We can see here that we pass in the list into the function, we can also pass in the item we want to count. Similar to other methods, this will return 0 if the item doesn’t exist.

In the next section, you’ll learn a naive implementation of how to count the number of times an item occurs in a list.

Want to learn how to calculate and use the natural logarithm in Python. Check out my tutorial here, which will teach you everything you need to know about how to calculate it in Python.

Use a For Loop to Count Number of Occurrences in a Python List

In this section, you’ll learn a naive implementation using Python for loops to count the number of times an item occurs in a given list. This method is intended to be illustrative, as it’s not nearly as practical as the other examples of this tutorial.

This section is broken into two parts: (1) count only one item and (2) return a dictionary of every item’s counts.

Let’s see how we can count a single item in a Python list using for loops:

# Count the Number of Occurrences in a Python list using a For Loop
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']
count = 0

for item in items:
    if item == 'a':
        count += 1

print(count)

# Returns: 3

We can see here that we instantiate a counter variable and set it to 0. We loop over every item in the list and evaluate if each item is equal to the item we want to count. If it is, then we increment the counter by 1.

Let’s see how we can return a dictionary that counts every item in a list, so that we can access the number of times each item appears in a list:

# Count the Number of Occurrences in a Python list using a For Loop
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']
counts = {}

for item in items:
    if item in counts:
        counts[item] += 1
    else:
        counts[item] = 1

print(counts.get('a'))

# Returns: 3

We can see here that we instantiate an empty dictionary. We then loop over each item in the list: if an item doesn’t exist in our dictionary, we assign it a value of 1. If the item already exists, then we increase the value by 1.

In the next section, you’ll learn how to use a Python list comprehension to return a dictionary with the number of times each item occurs in a list.

Want to learn more about Python for-loops? Check out my in-depth tutorial that takes your from beginner to advanced for-loops user! Want to watch a video instead? Check out my YouTube tutorial here.

Use a Dictionary Comprehension to Count Number of Occurrences in a Python List

Python dictionary comprehensions are powerful tools that let us generate new dictionaries by looping over an iterable item. In this case, we will loop over a Python list and generate a dictionary that allows us to count how many times an item appears in a list.

The image below shows how a Python dictionary comprehension works. If you want to read a detailed guide on how to use them, check out my tutorial here.

Python Dictionary Comprehension overview
How Dictionary comprehensions work in Python

Let’s see how we can use a Python dictionary comprehension to accomplish our goal:

# Count the Number of Occurrences in a Python list using a dictionary comprehension
items = ['a', 'b', 'a', 'c', 'd', 'd', 'd', 'c', 'a', 'b']
counts = {item:items.count(item) for item in items}

print(counts.get('a'))

# Returns: 3

In the example above, we use a comprehension to loop over our list. We loop over each item and assign the key to each item – for the value, we assign the count of each item in the list. Because Python dictionaries are required to have unique keys, Python implicitly handles assigning single keys.

Need to check if a key exists in a Python dictionary? Check out this tutorial, which teaches you five different ways of seeing if a key exists in a Python dictionary, including how to return a default value.

Conclusion

In this tutorial, you learned how to use Python to count the number of times an item appears in a given list. You learned how to do this using both the count method and the Counter class. You learned a number of other methods to accomplish this, including using Pandas and operator, for loops, and dictionary comprehensions.

Using the count method is preferable if you only need to count a single item. If you need to count multiple items, the Counter method is preferred.

To learn more about the Counter class from the collections library, check out the official documentation here.

Nik Piepenbreier

Nik is the author of datagy.io and has over a decade of experience working with data analytics, data science, and Python. He specializes in teaching developers how to use Python for data science using hands-on tutorials.View Author posts

Leave a Reply

Your email address will not be published. Required fields are marked *