Python Array count() Method
The Python array count() method accepts an element as a parameter is used to find number times an element occurred in the current array.
It accepts an element as a parameter and returns the number of occurrences. If the element is not found then it will return zero.
Syntax
Following is the syntax of python array count() method β
array_name.count(element)
Parameters
This method accepts a single value specifying the desired element as a parameter. This can be of any datatype.
Return Value
This method returns an integer value representing the number of occurrence of the given element.
Example 1
Following is the basic example of python array count() method β
import array as arr
#Creating an array
my_array1 = arr.array('i',[404, 150, 300, 150, 350])
#Printing the elements of an array
print("Array Elements are : ",my_array1)
element1 = 150
#counting element1
count = my_array1.count(element1)
print("count of ",element1,":", count)
Output
Here is the output of the above code β
Array Elements are : array('i', [404, 150, 300, 150, 350])
count of 150 : 2
Example 2
When the element is not present in an array, this method returns zero. Here is an example β
import array as arr
#Creating an array
my_array2 = arr.array('d',[3.5, 7.8, 3.5, 4.6, 5.6])
#Printing the elements of an array
print("Array Elements are : ", my_array2)
element2=1.5
#counting element2
count = my_array2.count(element2)
print("count of ",element2,": ", count)
Output
Array Elements are : array('d', [3.5, 7.8, 3.5, 4.6, 5.6])
count of 1.5 : 0
Example 3
If we pass more than one element as a parameter, It will accept the elements as tuple and returns zero β
import array as arr
my_array3 = arr.array('d',[14.5,56.9,44.9,89.2,64.9,76.4,56.9,89.2])
#Printing the elements of an array
print("Array Elements are : ", my_array3)
element3 = 56.9,89.2
#counting element3
z=my_array3.count(element3)
print("count of ",element3,": ", z)
Output
Following is the output of the above code β
Array Elements are : array('d', [14.5, 56.9, 44.9, 89.2, 64.9, 76.4, 56.9, 89.2])
count of (56.9, 89.2, 14.5) : 0
Example 4
In Python, Array is used to define only for numeric values. We use list for string datatype. List is similar to the array. We can define list instead of an array β
my_array4=['e','a','k','s','a','o','a']
element4='s'
x=my_array4.count(element4)
print("The count of ",element4,":",x)
Output
Following is the output of the above code β
The count of s : 1