Find the index of a value in a Range

Index of a value in a Range

To find the index of a value in a range object in Python, you can use range.index() method.

Call index() method on the range object, and pass the value as argument. The function returns in integer representing the index of the specified value in the given range.

Examples

1. Index of value when range contains the value

In the following program, we take a range object with start=0, stop=20, and step=3. We take a value 12, and find its index in the range using range.index() method.

Python Program

myrange = range(0, 20, 3)
value = 12
index = myrange.index(value)
print(f'Index of {value} in the range is {index}.')
Run Code Copy

Output

Index of 12 in the range is 4.

2. Index of value when range does not contain the value

In the following program, we take a range object with start=0, stop=20, and step=3. We take a value 13, and find its index in the range using range.index() method.

We have taken the range such that the specified value is not present in the range. When the specified value is not present, index() method throws ValueError, as shown in the following program.

Python Program

myrange = range(0, 20, 3)
value = 13
index = myrange.index(value)
print(f'Index of {value} in the range is {index}.')
Run Code Copy

Output

Traceback (most recent call last):
  File "example.py", line 3, in <module>
    index = myrange.index(value)
ValueError: 13 is not in range

Summary

In this tutorial of Python Ranges, we learned how to find the index of a specific value in given range using index() method of range class.

Code copied to clipboard successfully 👍