Python 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

AuthorAdmin

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

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