Find the First Matching Index
Checking your account…
Sign in to save your code and progress across devices. The lesson and problem statement remain public.
Loading the interactive Practice workspace.If it does not appear, the problem and learning material remain readable, but browser execution is unavailable.Reload Practice workspace
Problem
Implement first_index(values, target). Return the first matching index or -1 when target is absent. Do not use list.index.
Starter code
def first_index(values, target):
passTest cases
first-duplicate
{
"args": [
[
4,
2,
4,
7
],
4
]
}Expected: 0
missing
{
"args": [
[
1,
3
],
2
]
}Expected: -1
Wizard outline
- Step 1: Define absence
Return -1 for an empty search space. The sentinel is part of the public contract and anchors the loop fallback.
- Step 2: Inspect the current candidate
Recognize a match at the first position. Checking before moving preserves the earliest-index invariant.
- Step 3: Complete the monotone scan
Find the first match anywhere or prove absence. Enumerating in increasing index order makes the first returned match minimal.
Footguns and prerequisites
- Returning the last match violates the first-index contract.
- Calling list.index hides absence handling behind an exception.
- functions
- lists and tuples
- control flow
Reviewed references
Recommended approach and implementation
Enumerate values from left to right and return on the first equality.
Why it works: Indexes are visited in increasing order. Therefore the first equality is the smallest matching index; reaching the end proves absence.
def first_index(values, target):
for index, value in enumerate(values):
if value == target:
return index
return -1