What is the array count() function in Python?
Overview
An array in Python is used to store multiple values of the same data type in a single variable.
The count() method is used to return the number of occurrences of a value or item in an array.
Syntax
array.count(x)
x is the value we want to check for its number of occurrences.
Parameters
The parameter value of the count() method is the value or element whose count we want to take in the given array.
Return value
The count() method returns the number of occurrences of a value in an array.
Example
# importing the array moduleimport array as arr# creating an integer data type arrayx = arr.array('i', [1,2,3,4,5,6,1,2,3,2,4,7])# using the count function for the value 2 in the arrayy = x.count(2)# printing the number of countsprint('The number of occurrences of the value 2 in the array is: ', y)
Code explanation
- Line 2: We import the array module.
- Line 5: We use the
array.array()function to create an array variablex. - Line 8: We use the
count()function to take the count or number of occurrences of the number2in the array we created. - Line 11: We print the value of the occurrences.