Technical skill practice

Python index(): Find a Value and Handle a Missing Match

Python list.index(value) returns the position of the first matching value. Optional start and stop arguments restrict the search, but the returned position still refers to the original list. If there is no match in that range, index raises ValueError rather than returning -1.

Start with a small, explicit task

A fictional route visits Central twice. Find the first visit, search beyond it for the return visit, and inspect what happens when a bounded search excludes that return. This exercise uses label equality, not geographical distance or a unique stop identifier.

Run the complete example

This original example was checked with Python 3.12.14. Save it as python_index.py and run it with Python 3.12. It uses only the standard library. The assertions check the stated results.

Expected output

1 3

not found

stops = ["Depot", "Central", "Park", "Central", "Harbor"]
first = stops.index("Central")
second = stops.index("Central", first + 1)
try:
    stops.index("Central", 2, 3)
except ValueError:
    bounded = "not found"
else:
    raise AssertionError("expected no Central in that slice")
assert first == 1 and second == 3
assert bounded == "not found"
assert stops[second] == "Central"
print(first, second)
print(bounded)

Explain the result

The first match is at zero-based position 1. Starting the next search at 2 skips that first match and finds position 3. It returns 3, not 1, because start changes where the search begins rather than renumbering the list. The final lookup checks that this index still selects Central in the original sequence.

The bounded search covers position 2 but excludes its stop bound 3. Park is the only examined item, so ValueError is the expected result. The except branch deliberately handles this specific missing-match case. It does not suppress unrelated failures or assign a fake valid index.

Avoid these mistakes

Do not assume list.index behaves like a string find method that returns -1. An accidental -1 used as a list index selects the last item and can hide a missing-match bug. For many repeated searches, consider whether you need a lookup structure, but account for duplicate labels before replacing the sequence.

Questions, answered

Does index find every matching position?

No. It returns the first match in the requested search range. The example searches again after the first position.

Is the stop bound included?

No in this example. The Central at position 3 is excluded by stop=3.

Sources and examples

ResumizeAI team. Examples are fictional teaching material, not customer results. Replace sample details with your own facts.

Your experience. A complete resume.

Build in Resumize with ATS-friendly templates, guided editing and a live preview. Start free, then upgrade when you need more.

Free account required. Free-plan PDF exports include a watermark.