Python program to get the number of occurrences of a specified element in an array

Published by user on

In this post, we will look at the python program to get the number of occurrences of a specified element in an array.

There are two ways to get the count.

  1. Use in-built count() function
  2. Loop through array elements and count the occurrences
Input: [60, 1000, 70, 1000, 80, 1000, 90, 1000]
Find the occurrences of 1000 in the above array
Output: 4

As 1000 occurs 4 times. So the output is 4.

Let’s look at the programs now.

Use in-built count() function

# python program to
# count the number of occurrences
# of specified element in an array using count()
from array import *

# declare and initialize the array
array_integer = array('i', [80, 5, 90, 5, 100, 5, 110, 5])

# display the values in the array
print("Array values: "+str(array_integer))

# display the occurrences of the element
print("Occurrences of the integer 5 is: "+str(array_integer.count(5)))

Output

Array values: array('i', [80, 5, 90, 5, 100, 5, 110, 5])
Occurrences of the integer 5 is: 4

Algorithm

Step 1: Declare and initialize the input array
Step 2: Call the count() function with an array
Step 3: Display the result

Count occurrences using loop

# python program to find 
# the occurrences of 
# the specified element in an array
 
# Method to find the count of 
# the specified element in the array
def find_count(my_array, element):
     
    # store the count
    count=0
       
    # iterate each element
    # and count the occurrences
    # of the specified element
    for i in my_array:
        if i == element:
            count = count + 1
           
    return(count) 
     
input_array=[10, 6, 20, 6, 30] 
   
result = find_count(input_array, 6)
 
# print the array
print ('Original array :', input_array)

# print the value of count 
print ('Element 6 occurs %i times in an array.' %(result))

Output

Original array : [10, 6, 20, 6, 30]
Element 6 occurs 2 times in an array.

Algorithm

Step 1: Write a function find_count() that accepts an array and the element.
Step 2: Declare and initialize the array
Step 3: Call the find_count() function
Step 4: Display the count of the specified element

Categories: python