What is the operator.countOf method in Python?
What is the operator module?
The operator module is an in-built module in Python. The module provides functions equivalent to the intrinsic operators of Python. For example, we can use the operator.mul() method to multiply instead of the * operator.
The module’s functions come in handy when callable methods are given as arguments to another Python object.
countOf method
The countOf method is used to return the number of elements in a that are equal to b.
Syntax
operator.countOf(a, b)
Parameters
The countOf method takes two parameters:
a: This is a list or a string.b: This is the element we are interested in finding ina
Return value
The method returns the number of elements in a that are equal to b.
Code example
import operatora = "hello educative"b = "e"print("operator.countOf('%s', '%s') = %s" % (a, b, operator.countOf(a, b)))a = [1, 2, 3, 4]b = 5print("operator.countOf('%s', '%s') = %s" % (a, b, operator.countOf(a, b)))
Explanation
- Line 1: We import the
operatormodule. - Lines 3–4: We define
aandb. - Line 6: We obtain the count of
binausing thecountOf()method and print the result. - Lines 8–9: We define new values for
aandb. - Lines 11–14: We obtain the count of
binausing thecountOf()method.