What is the operator.indexOf() method in python?

What is the operator module?

The operator module is an built-in 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.

The indexOf() method

The indexOf() method takes two parameters. The syntax of the method is as follows:

operator.indexOf(a, b)

The method is used to return the index of the first occurrence of b in a. a here is iterable.

If b is not in a then the method raises a ValueError indicating b is not in a.

Code

import operator
a = "hello educative"
b = "e"
print("operator.indexOf('%s', '%s') = %s" % (a, b, operator.indexOf(a, b)))
a = [1, 2, 3, 4]
b = 5
try:
print("operator.indexOf('%s', '%s') = %s" % (a, b, operator.indexOf(a, b)))
except ValueError as ex:
print("%s not in %s" % (b, a))

Explanation

In the code above,

  • Line 1: operator module is imported.
  • Lines 3-4: Two strings a and b are initialized.
  • Line 6: The index of b in a is obtained using the indexOf() method and the result is printed.
  • Lines 8-9: New values for a and b are assigned.
  • Lines 11-14: The index of b in a is obtained using the indexOf() method. But the method throws a ValueError indicating that 5 is not present in [1, 2, 3, 4].

Free Resources