Thursday, August 28, 2025
HomeLanguagesPython Count Occurrences of an element in Array

Python Count Occurrences of an element in Array

Python program counts occurrences of an element in the array; Through this tutorial, you will learn how to count occurrences of each element in an array in python.

Python Count Occurrences of an element in Array

  • python program to count occurrences of in array using count.
  • python program to count occurrences of in array using for loop.
  • python program to count occurrences of in array using function.

Python program to count occurrences of in array using count.

# array list
arr = [1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8] 

# count element '2'
count = arr.count(2)

print(count)

After executing the program, the output will be:

4

Python program to count occurrences of in array using for loop

# function to count
def countOccurrences(arr, n, x): 
    res = 0
    for i in range(n): 
        if x == arr[i]: 
            res += 1
    return res 
   
# array list
arr = [1, 2, 2, 2, 2, 3, 4, 7 ,8 ,8] 

n = len(arr) 

x = 2

print (countOccurrences(arr, n, x)) 

After executing the program, the output will be:

4

Python program to count the occurrences in an array using function

#function to count occurence
def Count(x, nums):
    count = 0
    for num in nums:
        if num == x:
            count = count + 1

    return count

x = 2
#print result
print (Count(x, [1,2,3,4,2,2,2]))

After executing the program, the output will be:

4

Recommended Python Array Programs

  1. Python Program to Find the GCD of Two Numbers or Array
  2. Python | Program to Find the LCM of the Array Elements
  3. Python Program to Find Sum of All Array Elements
  4. Python: Find the Union and Intersection of Two Arrays
RELATED ARTICLES

Most Popular

Dominic
32245 POSTS0 COMMENTS
Milvus
80 POSTS0 COMMENTS
Nango Kala
6615 POSTS0 COMMENTS
Nicole Veronica
11787 POSTS0 COMMENTS
Nokonwaba Nkukhwana
11833 POSTS0 COMMENTS
Shaida Kate Naidoo
6729 POSTS0 COMMENTS
Ted Musemwa
7011 POSTS0 COMMENTS
Thapelo Manthata
6684 POSTS0 COMMENTS
Umr Jansen
6699 POSTS0 COMMENTS