Linear Search

intermediate20 min

Learning 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"]:

Stepindexvaluevalue == target?
10"Aisha"No
21"Tom"No
32"Priya"No
43"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.

Practise

Apply what you've just learned in the Coding Lab.

Open Coding Lab

Test yourself

Check your understanding with exam-style questions.

Go to Exam Practice
Log in to track this lesson on your progress dashboard.
Log in