API Navigator Logo

Finding an Item's Index in a Python List

Author: Newtum

This guide explains how to use the `.index()` method in Python to find the position (index) of the first occurrence of a specified value in a list.

Basic Usage of `.index()`

The `.index()` method searches the list for a specified item and returns its index. If the item is not found, it raises a `ValueError`.

fruits = ['apple', 'banana', 'cherry', 'banana']

# Find the index of 'cherry'
index_of_cherry = fruits.index('cherry')
print(f"The index of 'cherry' is: {index_of_cherry}")

# It returns the index of the *first* occurrence
index_of_banana = fruits.index('banana')
print(f"The index of the first 'banana' is: {index_of_banana}")

Handling `ValueError`

It's good practice to wrap your `.index()` call in a `try...except` block or to check for the item's existence first to avoid crashing your program if the item isn't in the list.

fruits = ['apple', 'banana', 'cherry']
item_to_find = 'orange'

# Method 1: Using try...except
try:
    index = fruits.index(item_to_find)
    print(f"Found '{item_to_find}' at index {index}")
except ValueError:
    print(f"'{item_to_find}' is not in the list.")

# Method 2: Using 'in' operator
if item_to_find in fruits:
    index = fruits.index(item_to_find)
    print(f"Found '{item_to_find}' at index {index}")
else:
    print(f"'{item_to_find}' is not in the list.")

Specifying Start and End Positions

You can also provide optional `start` and `end` arguments to search within a specific slice of the list.

numbers = [1, 2, 3, 4, 1, 2, 3, 4, 1, 2]

# Find the index of the number 1, starting the search from index 2
index_of_1 = numbers.index(1, 2)
print(f"Found 1 at index {index_of_1} (starting search from index 2)")

# Find the index of 3 between index 3 and 7
index_of_3 = numbers.index(3, 3, 7)
print(f"Found 3 at index {index_of_3} (between index 3 and 7)")