GCSE Python · Lesson 2 of 9

Linear search and Boolean flags

OCR J277 2.1 / AQA 8525 algorithms

Find a target in an unsorted list without using in or index().

← All GCSE Python lessons

Searching an unsorted list

Linear search checks one item after another until it finds the target or reaches the end. It works on unsorted data and has worst-case linear time relative to the list length. Trace which item is examined on each pass.

Watch out: Avoid reporting success just because the loop finishes. Track whether a match was actually found.

1 · Learn and predict

Read this worked example. Predict its output, run it in Python 3, and explain how variables change.

def linear_search(values, target):
    for position in range(len(values)):
        if values[position] == target:
            return position
    return -1

print(linear_search([9, 3, 6, 1], 6))

2 · Build independently

Find a target in an unsorted list without using in or index(). Work from the starter code before comparing with the solution.

Download starter + solution ZIP ↓

For a stretch challenge: add meaningful test data, handle an edge case and explain one design decision.

Reveal reference solution
def linear_search(values, target):
    for position in range(len(values)):
        if values[position] == target:
            return position
    return -1

numbers = [9, 3, 6, 1]
for target in [6, 7, 9]:
    position = linear_search(numbers, target)
    if position == -1:
        print(target, "not found")
    else:
        print(target, "found at", position)

The reference is one possible approach. Test your own program before comparing.

3 · Debug and explain

Question: Why must the loop check the entire list in the worst case?

Show explanation

If the target is absent or last, every item may need comparison.

4 · Check your understanding

What is the worst-case linear-search complexity?

5 · Reflect

Explain one test you used, one problem you solved and one improvement you would make.

This records completion only in this browser and does not certify mastery.

Want extra practice? Try interactive Python tracing and debugging questions →