Count occurrences of an element in a list in Python (original) (raw)

Last Updated : 21 Oct, 2024

A common task when working with **lists is to count how many times a specific element appears. In Python, we have several ways to count occurrences of an element using both built-in and custom methods.

The simplest and most straightforward way to count occurrences of an element in a list is by using the count() method, which is a built-in method specifically designed for this task.

Using count()

In this example, we have a list and we are counting the occurrences of **2 and **3 using the count() method.

Python `

a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]

Count occurrences of 2

print(a.count(2))

Count occurrences of 3

print(a.count(3))

`

Below are the other methods by which we can use to count the occurrences of an element in a list.

Table of Content

**Using a Loop

In this method, iterate over the list using loop (for loop) and keep a **counter variable to count the occurrences. Each time we find the target element, increase the counter by one.

Python `

a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]

Initial count is zero

count = 0

Iterate over the list

for val in a:

  # If num is equal to 3 
if val == 3:
  
    # Increase the counter
    count += 1

print(count)

`

Using countOf()

The **countOf() function is equivalent to using the **count() method of a list, but it comes from the **operator module.

It takes **two arguments: the sequence in which we want to count and the value that we want to count. Let's look at the syntax given below:

import operator

operator.countOf(sequence, value)

**Using Counter from collections

The Counter class from the collections module can count occurrences for all elements and returns the results as a dictionary. Let's see how can we use this to count occurrence of a single element.

Python `

from collections import Counter

a = [1, 3, 2, 6, 3, 2, 8, 2, 9, 2, 7, 3]

Create a counter objects

res = Counter(a)

Get count of 3

print(res[3])

`

**Note: This method is not efficient for finding occurrence of single element because it requires O(n) extra space to create a new dictionary. But this method is very efficient when finding all occurrences of elements.

**Related Articles: