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 in a

Return value

The method returns the number of elements in a that are equal to b.

Code example

import operator
a = "hello educative"
b = "e"
print("operator.countOf('%s', '%s') = %s" % (a, b, operator.countOf(a, b)))
a = [1, 2, 3, 4]
b = 5
print("operator.countOf('%s', '%s') = %s" % (a, b, operator.countOf(a, b)))

Explanation

  • Line 1: We import the operator module.
  • Lines 3–4: We define a and b.
  • Line 6: We obtain the count of b in a using the countOf() method and print the result.
  • Lines 8–9: We define new values for a and b.
  • Lines 11–14: We obtain the count of b in a using the countOf() method.

Free Resources