How to Count the Occurrences of a List Element

Rate this post

Problem Formulation and Solution Overview

In this article, you’ll learn how to count the occurrences of a selected List element in Python.

To make it more fun, we have the following running scenario:

A Teacher from Orchard Elementary would like a script created for the 4th-grade students called “Count-Me“. She would like this script to do the following:

  • First, generate and display 10 random numbers on a single line.
  • Next, generate and display one (1) random number to find.
  • Prompt for the total occurrences found.
  • Display a message validating the solution.

💬 Question: How would we write the Python code to accomplish this task?

We can accomplish this task by one of the following options:

  • Method 1: Use NumPy and count()
  • Method 2: Use operator countOf()
  • Method 3: Use a For Loop
  • Method 4: Use a Counter()

Preparation

Before any data manipulation can occur, one (1) new library will require installation.

  • The NumPy library supports multi-dimensional arrays and matrices in addition to a collection of mathematical functions.

To install this library, navigate to an IDE terminal. At the command prompt ($), execute the code below. For the terminal used in this example, the command prompt is a dollar sign ($). Your terminal prompt may be different.

$ pip install numpy

Hit the <Enter> key on the keyboard to start the installation process.

If the installation was successful, a message displays in the terminal indicating the same.


Feel free to view the PyCharm installation guide for the required library.


Add the following code to the top of each code snippet. This snippet will allow the code in this article to run error-free.

import numpy as np
import random
import operator
from collections import Counter

💡 Note: The counter and collections libraries are built-in to Python and do not require installation.


Method 1: Use NumPy and count()

To count the total occurrences of an element inside a List, this example will use NumPy and the count() function.

the_list  = list(np.random.choice(20, 20))
dup_num   = the_list[random.randint(0, 19)]
dup_count = the_list.count(dup_num)

try:
    print(the_list)
    check = int(input(f'How man times does the number {dup_num} appear in the list? '))
    if check == dup_count:
        print(f'Correct! The answer is {check}.')
    else:
        print(f'Sorry! Try again!')
except ValueError:
        print(f'Incorrect value. Bye')

The previous code snippet performs the following steps:

  • Our first line generates and saves 20 random numbers to the_list.
  • Next, dup_num is created by generating and saving one (1) random number from the_list.
  • Finally, we determine how many occurrences of dup_num were found using count().
  • The result saves to dup_count.

Inside the try statement, the_list is output to the terminal.

The user is prompted to enter the total number of occurrences. To confirm, the user presses the <Enter> key. The value entered is then compared to dup_count, and a message indicates the outcome.

💡 Note: Click here for details on the try/except statement.


Method 2: Use operator countOf()

To count the total occurrences of a specified element inside a List, this example will use the countOf() function.

the_list  = [random.randrange(0, 20) for num in range(20)]
dup_num   = the_list[random.randint(0, 19)]
dup_count = operator.countOf(the_list, dup_num)

try:
    print(the_list)
    check = int(input(f'How man times does the number {dup_num} appear in the list? '))
    if check == dup_count:
        print(f'Correct! The answer is {check}.')
    else:
        print(f'Sorry! Try again!')
except ValueError:
        print(f'Incorrect value. Bye')

This code snippet performs the following steps:

  • Our first line generates and saves 20 random numbers to the_list.
  • Next, dup_num is created by generating and saving one (1) random number from the_list.
  • Finally, we determine how many occurrences of dup_num were found using operator.countOf().
  • The result saves to dup_count.

Inside the try statement, the_list is output to the terminal.

The user is prompted to enter the total number of occurrences. To confirm, the user presses the <Enter> key.

The value entered is then compared to dup_count, and a message indicates the outcome.


Method 3: Use a For Loop

To count the total occurrences of a specified element inside a List, this example will use the For Loop.

the_list  = [random.randrange(0, 20) for num in range(20)]
dup_num   = the_list[random.randint(0, 19)]

dup_count = 0
for i in the_list:
    if i == dup_num:
        dup_count += 1

try:
    print(the_list)
    check = int(input(f'How man times does the number {dup_num} appear in the list? '))
    if check == dup_count:
        print(f'Correct! The answer is {check}.')
    else:
        print(f'Sorry! Try again!')
except ValueError:
        print(f'Incorrect value. Bye')

The previous code snippet performs the following steps:

  • Our first line generates and saves 20 random numbers to the_list.
  • Next, dup_num is created by generating and saving one (1) random number from the_list.
  • Finally, a For Loop is instantiated. Upon each Loop, the element is matched against dup_num.
  • If found, dup_count is increased by one (1).

Inside the try statement, the_list is output to the terminal.

The user is prompted to enter the total number of occurrences. To confirm, the user presses the <Enter> key.

The value entered is then compared to dup_count, and a message indicates the outcome.


Method 4: Counter()

To count the total occurrences of a specified element inside a List, this example will use the Counter() initializer method.

the_list  = [random.randrange(0, 20) for num in range(20)]
dup_num   = the_list[random.randint(0, 19)]
d = Counter(the_list)
dup_count = d[dup_num]

try:
    print(the_list)
    check = int(input(f'How man times does the number {dup_num} appear in the list? '))
    if check == dup_count:
        print(f'Correct! The answer is {check}.')
    else:
        print(f'Sorry! Try again!')
except ValueError:
        print(f'Incorrect value. Bye')

The previous code snippet performs the following steps:

  • Our first line generates and saves 20 random numbers to the_list.
  • Next, dup_num is created by generating and saving one (1) random number from the_list.
  • Finally, a For Loop is instantiated. Upon each Loop, an element is matched against dup_num.
  • If found, dup_count is increased by one (1).

Inside the try statement, the_list is output to the terminal.

The user is prompted to enter the total number of occurrences. To confirm, the user presses the <Enter> key.

The value entered is then compared to dup_count, and a message indicates the outcome.


Summary

These four (4) methods of counting occurrences of a specified element inside a List should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!