Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] How to Count the Occurrences of a List Element
1
How to Count the Occurrences of a List Element

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.

[Image: 1f4ac.png] 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
    Code:
    count()


  • Method 2: Use operator
    Code:
    countOf()

  • Method 3: Use a For Loop

  • Method 4: Use a
    Code:
    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 (
Code:
$
), execute the code below. For the terminal used in this example, the command prompt is a dollar sign (
Code:
$
). Your terminal prompt may be different.

Code:
$ pip install numpy

Hit the
Code:
<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.

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

[Image: 1f4a1.png] Note: The
Code:
counter
and
Code:
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 NumPyand the
Code:
count()
function.

Code:
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
    Code:
    the_list
    .

  • Next,
    Code:
    dup_num
    is created by generating and saving one (1) random number from
    Code:
    the_list
    .

  • Finally, we determine how many occurrences of
    Code:
    dup_num
    were found using
    Code:
    count()
    .

  • The result saves to
    Code:
    dup_count
    .

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

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

[Image: 1f4a1.png] 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
Code:
countOf()
function.

Code:
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
    Code:
    the_list
    .

  • Next,
    Code:
    dup_num
    is created by generating and saving one (1) random number from
    Code:
    the_list
    .

  • Finally, we determine how many occurrences of
    Code:
    dup_num
    were found using
    Code:
    operator.countOf()
    .

  • The result saves to
    Code:
    dup_count
    .

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

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

The value entered is then compared to
Code:
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.

Code:
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
    Code:
    the_list
    .

  • Next,
    Code:
    dup_num
    is created by generating and saving one (1) random number from
    Code:
    the_list
    .

  • Finally, a For Loop is instantiated. Upon each Loop, the element is matched against
    Code:
    dup_num
    .

  • If found,
    Code:
    dup_count
    is increased by one (1).

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

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

The value entered is then compared to
Code:
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
Code:
Counter()
initializer method.

Code:
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
    Code:
    the_list
    .

  • Next,
    Code:
    dup_num
    is created by generating and saving one (1) random number from
    Code:
    the_list
    .

  • Finally, a For Loop is instantiated. Upon each Loop, an element is matched against
    Code:
    dup_num
    .

  • If found,
    Code:
    dup_count
    is increased by one (1).

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

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

The value entered is then compared to
Code:
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!
Reply

Users browsing this thread:
1 Guest(s)


Forum Jump: