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

Leave a Reply

Your email address will not be published. Required fields are marked *

Back to top button