04-16-2022, 03:53 PM
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:
Question: How would we write the Python code to accomplish this task?
We can accomplish this task by one of the following options:
Preparation
Before any data manipulation can occur, one (1) new library will require installation.
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.
Hit the 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.
Note: The and 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 function.
The previous code snippet performs the following steps:
Inside the statement, is output to the terminal.
The user is prompted to enter the total number of occurrences. To confirm, the user presses the key. The value entered is then compared to , 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 function.
This code snippet performs the following steps:
Inside the statement, is output to the terminal.
The user is prompted to enter the total number of occurrences. To confirm, the user presses the key.
The value entered is then compared to, 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 previous code snippet performs the following steps:
Inside the statement, is output to the terminal.
The user is prompted to enter the total number of occurrences. To confirm, the user presses the key.
The value entered is then compared to, 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 initializer method.
The previous code snippet performs the following steps:
Inside the statement, is output to the terminal.
The user is prompted to enter the total number of occurrences. To confirm, the user presses the key.
The value entered is then compared to, 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!
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 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:
$Code:
$Code:
$ pip install numpyHit the
Code:
<Enter>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
Note: The Code:
counterCode:
collectionsMethod 1: Use NumPy and count()
To count the total occurrences of an element inside a List, this example will use NumPyand the
Code:
count()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, is created by generating and saving one (1) random number fromCode:
dup_num.Code:the_list
- Finally, we determine how many occurrences of were found usingCode:
dup_num.Code:count()
- The result saves to .Code:
dup_count
Inside the
Code:
tryCode:
the_listThe user is prompted to enter the total number of occurrences. To confirm, the user presses the
Code:
<Enter>Code:
dup_count
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()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, is created by generating and saving one (1) random number fromCode:
dup_num.Code:the_list
- Finally, we determine how many occurrences of were found usingCode:
dup_num.Code:operator.countOf()
- The result saves to .Code:
dup_count
Inside the
Code:
tryCode:
the_listThe user is prompted to enter the total number of occurrences. To confirm, the user presses the
Code:
<Enter>The value entered is then compared to
Code:
dup_countMethod 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, is created by generating and saving one (1) random number fromCode:
dup_num.Code:the_list
- Finally, a For Loop is instantiated. Upon each Loop, the element is matched against .Code:
dup_num
- If found, is increased by one (1).Code:
dup_count
Inside the
Code:
tryCode:
the_listThe user is prompted to enter the total number of occurrences. To confirm, the user presses the
Code:
<Enter>The value entered is then compared to
Code:
dup_countMethod 4: Counter()
To count the total occurrences of a specified element inside a List, this example will use the
Code:
Counter()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, is created by generating and saving one (1) random number fromCode:
dup_num.Code:the_list
- Finally, a For Loop is instantiated. Upon each Loop, an element is matched against .Code:
dup_num
- If found, is increased by one (1).Code:
dup_count
Inside the
Code:
tryCode:
the_listThe user is prompted to enter the total number of occurrences. To confirm, the user presses the
Code:
<Enter>The value entered is then compared to
Code:
dup_countSummary
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!

