Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

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

abhilash

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code

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))
Applying the indexOf() method

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].

RELATED TAGS

python
communitycreator

Grokking Modern System Design Interview for Engineers & Managers

Ace your System Design Interview and take your career to the next level. Learn to handle the design of applications like Netflix, Quora, Facebook, Uber, and many more in a 45-min interview. Learn the RESHADED framework for architecting web-scale applications by determining requirements, constraints, and assumptions before diving into a step-by-step design process.

Answers Code
Keep Exploring