Python count occurrences in array; Through this tutorial, i am going to show you how to count occurrences in numpy, list array in python.
In this tutorial, i will write python programs to count occurrences in numpy, list with fastest way.
Python Count the Occurrences in an Array
There are three different way to count occurrences in numpy, list array in python; as show below:
- 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
Be First to Comment