Home »
Python »
Python Programs
Python program to find the occurrence of a particular number in an array
Count occurrences of an element in an array: Here, we are going to learn how to find the occurrence of a particular number in an array using python program?
By Suryaveer Singh Last updated : January 14, 2024
In this article, we would learn about arrays and how to code for an array question asked? So starting off we would first learn about arrays i.e. what an array is?
ARRAY
An array can be defined as a container object that is used to hold a fixed number of values of a single type of data. The main purpose of an array is to store multiple items of the same type together.
Image source: https://cdncontribute.geeksforgeeks.org/wp-content/uploads/array-2.png
This is the simple idea that you need to understand about the array, now starting with the simple question.
Problem statement
Suppose you are given with an array that contains ints. Your task is to return the number of 3 in the array.
Example
Consider the below example with sample input and output:
count_occurrence([1, 2, 3], 3) = 1
count_occurrence([1, 3, 3], 3) = 2
count_occurrence([1, 3, 9, 3, 3], 3) = 3
Solution approach
Here we have to again consider a variable which is initially equal to zero to keep the count of a number of 3 and also our function is only defined for nums as our array would only contain integers as mentioned earlier.
Algorithm
The below are the algorithm steps to find the occurrence of a particular number in an array/list:
- Take a list of integers (an array) and a number whose occurrence is to be found.
- Create a function (count_occurrence()), pass list (numlist), and number (num).
- Define a counter variable (count) and initiate it with 0
- Inside the function, iterate the list.
- Compare each list element (value) with the given number (num) , if the list element is equal to the number, increase the value of the count.
- Return the count, that is the occurrences of the given number (num).
Python program to find the occurrence of a particular number in an array
# Function that accepts a list and a number
# and, returns the count of the given number
def count_occurrence(numlist, num):
count = 0
for value in numlist:
if value == num:
count = count + 1
return count
# Main code
# Call the function
# Create a list
list1 = [1, 2, 3, 4, 3, 3, 3]
print("List is:", list1)
# Find occurrence of 3 in list
print("Occurrence of 3:", count_occurrence(list1, 3))
# Find occurrence of 1 in list
print("Occurrence of 1:", count_occurrence(list1, 1))
# Find occurrence of 4 in list
print("Occurrence of 4:", count_occurrence(list1, 4))
Output
The output of the above program is:
List is: [1, 2, 3, 4, 3, 3, 3]
Occurrence of 3: 4
Occurrence of 1: 1
Occurrence of 4: 1
To understand the above program, you should have the basic knowledge of the following Python topics:
Python Array Programs »