Locate the First Match with Linear Search
Core idea
Linear search checks values in order until a match or exhaustion. It works on unsorted lists and can return the first matching zero-based index, or a documented sentinel such as -1. Before examining index i, no earlier item matches. Worst-case time is O(n), auxiliary space O(1) for bounded values.
def locate(values, target): for i, value in enumerate(values): if value == target: return i return -1print(locate([8, 3, 8], 8))The first matching index is returned immediately.
Handle missing and empty lists
def locate(values, target): for i, value in enumerate(values): if value == target: return i return -1print(locate([2, 7], 9))print(locate([], 9))Both paths exhaust the input without a match.
Common mistake
Do not use the sentinel -1 as a valid Python list index without checking it: Python interprets it as the final item. Do not return inside the loop on the first mismatch.
Practice
Find the first occurrence of a target ID, returning -1 if absent. Test duplicates, empty input and a last-position match.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Linear search
Check your understanding of linear search.
What is printed?
def locate(values, target): for i, value in enumerate(values): if value == target: return i return -1print(locate([5,2,5],2))What is printed?
def locate(values, target): for i, value in enumerate(values): if value == target: return i return -1print(locate([2,3],4))What ordering does linear search require?
Why check -1 before indexing?