Skip to content

Module 18 · Algorithms and Problem Solving — topic 8 of 18

Linear search

Searching item by item: the linear search algorithm, returning an index or -1, finding all matches, searching records by a condition, counting comparisons, and when linear search is the right choice.

Beginner 8 min read·Lesson 268 of 306 in Python Programming

Learning objectives

  • Implement linear search
  • Find all matches and search by condition
  • Analyse best, worst and average cases

Definition

Linear (sequential) search checks each element of a collection in order until it finds the target or reaches the end. It works on any sequence, sorted or not, and takes O(n) time in the worst case.

Introduction

Looking for a friend's name on an unsorted attendance sheet, you read from the top until you find it. That's linear search.

Why it matters

Linear search is simple, works on unsorted data and is often the right choice for small lists. It is also the baseline every faster search is compared with.

Detailed explanation

Check each item in turn; when it matches, return its position. If the loop finishes, the target isn't present — return -1 or None.

Returning as soon as a match is found (early exit) avoids unnecessary work.

Best case: the target is first (1 comparison). Worst case: it's last or missing (n comparisons). Average case for a present item: about n / 2.

Python's in operator, list.index and list.count all perform linear searches internally.

Linear search works on any iterable, including unsorted lists, strings, files read line by line and generators.

Searching by condition (the first student with roll number 7) uses the same pattern; next() with a generator expression expresses it concisely.

For repeated searches on large data, sort once and use binary search, or build a set or dictionary for O(1) lookups.

Linear search is stable in the sense that it finds the first occurrence; finding all occurrences requires scanning to the end.

Syntax

Python
def linear_search(items, target):
for i, item in enumerate(items):
if item == target:
return i
return -1
  • Check items in order.
  • Return early on a match.
  • O(n) worst case.

Code examples

Finding a position

Python
def linear_search(items, target):
for i, item in enumerate(items):
if item == target:
return i
return -1
nums = [7, 3, 9, 3, 5]
print(linear_search(nums, 3), linear_search(nums, 8), nums.index(9), 8 in nums)
Output
1 -1 2 False

All matches and conditions

Python
def find_all(items, target):
return [i for i, x in enumerate(items) if x == target]
print(find_all("banana", "a"))
students = [{"name": "Asha", "roll": 12}, {"name": "Ravi", "roll": 7}]
print(next((s for s in students if s["roll"] == 7), None))
Output
[1, 3, 5]
{'name': 'Ravi', 'roll': 7}

More examples

Counting comparisons

Python
def search_count(items, target):
comparisons = 0
for i, item in enumerate(items):
comparisons += 1
if item == target:
return i, comparisons
return -1, comparisons
data = list(range(1, 101))
print(search_count(data, 1), search_count(data, 100), search_count(data, 500))
average = sum(search_count(data, t)[1] for t in data) / len(data)
print(average)
Output
(0, 1) (99, 100) (-1, 100)
50.5

Step-by-step explanation

  • Finding the first item takes one comparison — the best case.
  • Finding the last item or a missing one takes all 100 comparisons — the worst case.
  • Averaged over every possible target, a search takes 50.5 comparisons, about n / 2.

Expected output

Running “Counting comparisons” prints exactly:

TextOutput
(0, 1) (99, 100) (-1, 100)
50.5

Practical applications

  • Searching a short menu or an unsorted log.
  • Finding the first record that matches a filter.

Best practices

  • Return early on a match.
  • Use in, index or next() for simple cases.
  • Switch to sets or binary search for repeated large searches.

Common mistakes

Returning inside the else of the loop body

Avoid

for i, x in enumerate(items):
if x == target:
return i
else:
return -1

Prefer

for i, x in enumerate(items):
if x == target:
return i
return -1

The wrong version gives up after checking only the first item.

Important notes

  • A 'sentinel' variant places the target at the end to remove one comparison per step; in Python the gain is negligible.

Key takeaways

  • Linear search checks each item in order.
  • O(1) best, O(n) worst and average.
  • Works on unsorted data.

Try it yourself

  1. 1
    Write a function that returns the index of the last occurrence of a value.
  2. 2
    Search a list of products for the first one under a given price.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

16 questions cover the “Algorithms and Problem Solving” module. Answers and explanations are revealed after you submit.

  • AdvancedWhat is printed?
  • AdvancedWhat is the average time complexity of x in my_set?
  • AdvancedA loop over a list checks item in other_list for each item. With both lists of length n, the complexity is…
Practise this module