What is count() method from array in Python?
Overview
Python is a high-level programming language that provides functionalities for several operations. The array module comes with various methods to manipulate array data structures.
The count(x) function counts the specified value x occurrences.
Syntax
counts = array.count(x)
Parameters
x: The specified value to be counted in the array.
Return value
This function returns the number of occurrences of x.
Code
Let’s look at the code below:
#import modulefrom array import array#initialize array with integer valuesarray_one = array("i", [1, 2, 3, 4, 5, 3, 6])#initialize array with double valuesarray_two = array("d", [6.4, 2.2, 8.7])#initialize array with double valuesarray_three = array("d", [5.72, 7.48, 0.43])#initialize array with signed valuesarray_four = array("b", [-7, +8, -10, +14, -7, -7])print (array_one)#find count of 3print("Count of 3:",array_one.count(3))print ("\n")print (array_two)#find count of 2.2print("Count of 2.2:",array_two.count(2.2))print ("\n")print (array_three)#find count of 0.2print("Count of 0.2:",array_three.count(0.2))print ("\n")print (array_four)#find count of -7print("Count of -7:",array_four.count(-7))
Explanation
In the code above:
-
Line 2: We import the
arraymodule. -
Line 5: We initialize an array with data type
integerin two arrays with data typedoublein lines 8 and 11, and an array with data typesigned integerin line 14. -
We then print each array and the count of a particular value.
-
Line 18: We print the count of 3 in
array_oneby passing3as a parameter in thearray.count()function. -
Line 23: We print the count of
2.2inarray_two. -
Line 28: We print the count of
0.2inarray_three. -
Line 33: We print the count of
-7inarray_four.