Python Count occurrence
Use .count() method to find occurrence of element in sequence. It is like searching the element and count its occurrence.
Argument is mandatory.
Syntax:variable.count( x )Return Value:
Zero or positive numberUse
- len - How many elements?
- .count() - How many times this element is present?
- .index() - What is the index / position of this element?
List count
# Example, List count
a1 = [1, 2, 3, "Hi", 1.2, 3]
# find count of element value 4
count1 = a1.count(4) # assigns 0
a1.count(3) # returns 2
a1.count(1.2) # returns 1
Tuple count
# Example, Tuple count
my_tuple = (1, 2, 3, "Hi", 1.2, 3)
# find count of element value 4
count1 = my_tuple.count(4) # assigns 0
my_tuple.count(3) # returns 2
my_tuple.count(1.2) # returns 1
Array count
# Example, Count occurrence of element in array
import array
a1 = array.array('l', [1, 10, 100, 1, 10, 100, 1, 2, 3] )
a1.count(-1) # returns 0
occurrence = a1.count(0) # assigns 0
occurrence = a1.count(1) # assigns 3
Count float element in array
Using array.count() for typecode 'f' might not work.
# Example, Count float element in array
import array
a1 = array.array('f', (1.1, 2.9, 9.13))
print(a1) # array('f', [1.100000023841858, 2.9000000953674316, 9.130000114440918])
a1.count(1.1) # returns 0
a1 = array.array('d', (1.1, 2.9, 9.13))
print(a1) # array('d', [1.1, 2.9, 9.13])
a1.count(1.1) # returns 1