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.
indexOf()
methodThe 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
.
import operatora = "hello educative"b = "e"print("operator.indexOf('%s', '%s') = %s" % (a, b, operator.indexOf(a, b)))a = [1, 2, 3, 4]b = 5try:print("operator.indexOf('%s', '%s') = %s" % (a, b, operator.indexOf(a, b)))except ValueError as ex:print("%s not in %s" % (b, a))
In the code above,
operator
module is imported.a
and b
are initialized.b
in a
is obtained using the indexOf()
method and the result is printed.a
and b
are assigned.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]
.