OneBite.Dev - Coding blog in a bite size

count the number of occurrences of a specific element in an array in python

Code snippet on how to count the number of occurrences of a specific element in an array in python

def count_occurrences(arr, x): 
    count = 0
    for i in range(len(arr)): 
        if arr[i] == x: 
            count += 1
    return count 

This code takes in an array (arr) and an element (x) as parameters and returns the number of occurrences of the element in the array. It starts by setting a count variable to 0. It then loops through the array, checking each element to see if it matches the element you passed in (x). If it does, the count increases by 1. Finally, when it has looped through the entire array, it returns the count.

python