Create an account


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.

? 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!




https://www.sickgaming.net/blog/2022/04/...t-element/
Reply



Possibly Related Threads…
Thread Author Replies Views Last Post
  [Tut] Collections.Counter: How to Count List Elements (Python) xSicKxBot 0 1,953 08-19-2023, 06:03 AM
Last Post: xSicKxBot
  [Tut] Python | Split String and Count Results xSicKxBot 0 1,160 11-26-2022, 06:39 AM
Last Post: xSicKxBot
  [Tut] Easiest Way to Convert List of Hex Strings to List of Integers xSicKxBot 0 1,456 11-25-2022, 11:54 AM
Last Post: xSicKxBot
  [Tut] Python | Split String and Get Last Element xSicKxBot 0 1,233 11-07-2022, 11:10 PM
Last Post: xSicKxBot
  [Tut] How to Count the Number of Unique Values in a List in Python? xSicKxBot 0 1,347 10-19-2022, 03:08 AM
Last Post: xSicKxBot
  [Tut] How to Retrieve a Single Element from a Python Generator xSicKxBot 0 1,195 09-30-2022, 11:20 AM
Last Post: xSicKxBot
  [Tut] Python Find Shortest List in List xSicKxBot 0 1,370 09-25-2022, 03:42 AM
Last Post: xSicKxBot
  [Tut] Python Find Longest List in List xSicKxBot 0 1,298 09-23-2022, 02:19 PM
Last Post: xSicKxBot
  [Tut] How to Find the Most Common Element in a Python Dictionary xSicKxBot 0 1,093 09-09-2022, 12:16 PM
Last Post: xSicKxBot
  [Tut] Python – Finding the Most Common Element in a Column xSicKxBot 0 1,209 09-06-2022, 10:19 PM
Last Post: xSicKxBot

Forum Jump:


Users browsing this thread:

Forum software by © MyBB Theme © iAndrew 2016