Linear Search
intermediate20 minLearning objectives
- Explain how linear search operates
- Trace linear search algorithms
- Implement linear search in Python
- Evaluate when linear search is appropriate
Learn
AQA 4.3.4 — Linear search
Retrieval: linear search operates on the array structures from Sequence 4 - the students list below is exactly the kind of array you indexed directly in that sequence; here you're searching it instead of accessing a known position.
Linear (sequential) search checks every item, one at a time, from the start, until it finds a match or reaches the end.
def linear_search(items, target):
for index, value in enumerate(items):
if value == target:
return index
return -1
Works on any list — sorted or not. Worst case: every item is checked — O(n).
Worked example — searching student records
students = ["Aisha", "Tom", "Priya", "Liam"]
result = linear_search(students, "Priya")
print(result) # 2
Trace it by hand
Searching for "Liam" in ["Aisha", "Tom", "Priya", "Liam"]:
| Step | index | value | value == target? |
|---|---|---|---|
| 1 | 0 | "Aisha" | No |
| 2 | 1 | "Tom" | No |
| 3 | 2 | "Priya" | No |
| 4 | 3 | "Liam" | Yes — return 3 |
Common mistake
Returning -1 for "not found" is a Python convention, not a universal rule — some languages/pseudocode use None, null, or a Boolean "found" flag instead. Always check what a specific exam question or codebase expects rather than assuming -1 everywhere.
Challenge
Modify linear_search to return all matching indexes (as a list) rather than stopping at the first match — useful if a search term could appear more than once.