Sub topic 2
Linear Search: Checking Every Element
This chapter assumes you can write loops, conditionals, and functions in Python or Java, and that you know zero-based indexing. You will build linear search, adapt it to related questions such as "the last match", "all matches", or "the first element that meets a condition", and study the mistakes people make most often when they write it. Running-time analysis comes in the next chapter. Here the focus is on writing it correctly.
The Core Idea
Linear search, also called sequential search, looks at the elements of a collection one at a time, in order. At each one it asks whether this is the element it wants. It stops at the first match, or it reports failure after checking the last element.
Linear search assumes almost nothing about the data:
- The data does not need to be sorted.
- The data does not need random access, so a linked list, a file stream, or a generator works too.
- The elements only need to support an equality test, or more generally a yes/no test.
Most other search methods rely on structure such as sorting, hashing, or a tree. Linear search needs none, so it is the method you can always fall back on.
A Reference Implementation
def linear_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
return -1
print(linear_search([4, 2, 7, 1], 7)) # 2
print(linear_search([4, 2, 7, 1], 5)) # -1
print(linear_search([], 5)) # -1Three details matter in this implementation:
enumerateyields the index and the value together. You avoid writingitems[i]by hand, and the function works on any iterable, not only on lists.- The early
returnstops at the first match. If the list contains duplicates, you get the lowest index. return -1comes after the loop. The function can only say "not found" once every element has been checked.
The empty list needs no special case. The loop body never runs and the function returns -1. If your version needs an if not items: guard to handle the empty list, its structure is probably wrong.
The Same Algorithm in Java
Java separates primitive comparison from object comparison. Use == for int. Use equals for objects, because == on objects only checks whether two references point to the same object. Objects.equals also handles null safely.
import java.util.Objects;
public class LinearSearch {
static int linearSearch(int[] a, int target) {
for (int i = 0; i < a.length; i++) {
if (a[i] == target) {
return i;
}
}
return -1;
}
static <T> int linearSearch(T[] a, T target) {
for (int i = 0; i < a.length; i++) {
if (Objects.equals(a[i], target)) {
return i;
}
}
return -1;
}
public static void main(String[] args) {
System.out.println(linearSearch(new int[]{4, 2, 7, 1}, 7)); // 2
String[] names = {"ada", "alan", "grace"};
String query = new String("grace"); // a distinct String object
System.out.println(linearSearch(names, query)); // 2
String[] withNull = {"x", null, "y"};
System.out.println(linearSearch(withNull, null)); // 1
}
}If the generic version used a[i] == target, the query lookup would return -1. The array holds a different String object with the same characters, and == compares references, not contents.
Variations on the Question
Linear search is a pattern more than a single function. Changing the scan order or the stopping condition answers different questions.
Last occurrence
To find the last match, scan from the end and stop at the first match you meet:
def linear_search_last(items, target):
for i in range(len(items) - 1, -1, -1):
if items[i] == target:
return i
return -1
print(linear_search_last([3, 1, 3, 2], 3)) # 2
print(linear_search_last([3, 1, 3, 2], 9)) # -1range(len(items) - 1, -1, -1) counts down to index 0. The stop value is -1 because range excludes its stop value. Writing 0 there would skip the first element.
All occurrences
If you need every match, you cannot stop early:
def find_all(items, target):
return [i for i, value in enumerate(items) if value == target]
print(find_all([3, 1, 3, 2, 3], 3)) # [0, 2, 4]
print(find_all([3, 1, 3, 2, 3], 7)) # []An empty list is a natural "not found" result here, so this version needs no sentinel value such as -1.
Search by predicate
A predicate is a function that returns True or False. Searching by predicate generalizes equality. It covers cases like "find the first user over 30" or "find the first line that starts with ERROR".
def find_first(items, predicate):
for i, value in enumerate(items):
if predicate(value):
return i
return -1
users = [
{"name": "Ana", "age": 25},
{"name": "Bo", "age": 34},
{"name": "Cy", "age": 41},
]
print(find_first(users, lambda u: u["age"] > 30)) # 1
print(find_first(users, lambda u: u["name"] == "Zed")) # -1Equality search is the special case find_first(items, lambda v: v == target).
What Python Already Gives You
You will rarely write a plain equality search by hand in Python. The built-in tools below all perform linear search internally.
| Tool | Returns | When not found |
|---|---|---|
| `target in items` | `True` / `False` | `False` |
| `items.index(target)` | first index | raises `ValueError` |
| `items.count(target)` | number of matches | `0` |
| `next((i for i, v in enumerate(items) if cond(v)), -1)` | first matching index | the default you pass |
items = [4, 2, 7, 1]
print(7 in items) # True
print(items.index(7)) # 2
try:
items.index(5)
except ValueError:
print("5 not found") # 5 not found
first_even_index = next((i for i, v in enumerate(items) if v % 2 == 0), -1)
print(first_even_index) # 0The next(generator, default) idiom is the Pythonic one-line predicate search. The generator stops evaluating as soon as next takes the first value, so it keeps the early exit.
Choosing a "Not Found" Signal
Different languages and libraries report a failed search in different ways. Each convention has a cost.
| Convention | Example | Risk |
|---|---|---|
| Return `-1` | C, Java `indexOf` | In Python, `items[-1]` is valid and returns the last element |
| Return `None` / `null` | many Python helpers | `if result:` is wrong when the match is at index 0 |
| Raise an exception | Python `list.index` | Costly or noisy if misses are common |
| Return `Optional` | Java `Optional<Integer>` | More verbose, but the caller must handle absence |
Common Mistakes
Returning "not found" inside the loop
This is the most common bug:
def broken_search(items, target):
for i, value in enumerate(items):
if value == target:
return i
else:
return -1 # bug: gives up after the first element
print(broken_search([4, 2, 7, 1], 7)) # -1, but the answer is 2The else branch exits on the first mismatch, so the function only ever checks items[0]. The failure return belongs after the loop.
Off-by-one loop bounds
Writing for i in range(len(items) - 1) skips the last element. Writing for (int i = 0; i <= a.length; i++) in Java reads one past the end and throws ArrayIndexOutOfBoundsException. Iterating with enumerate or Java's enhanced for loop removes this whole class of bug. Use an explicit index only when you need one.
Truthiness checks on the result
idx = linear_search([7, 8, 9], 7) # 0
if idx:
print("found") # never prints: 0 is falsyCompare explicitly with if idx != -1: or if idx is not None:.
Mutating the collection while scanning
Removing elements from a list while iterating over it shifts the remaining elements left, and the loop skips the element that moves into the current slot. Build a new list instead, or collect indices first and delete afterward.
Equality surprises
What counts as a match depends on how equality is defined for the element type:
- Floating-point values that print the same can differ:
0.1 + 0.2 == 0.3isFalse. Search with a tolerance predicate such asabs(v - x) < 1e-9. float('nan') == float('nan')isFalse. Python'sinand.index()check identity before equality, so a list finds the same NaN object but not a freshly created one.- In Java, a class that does not override
equalsfalls back to reference identity. Two objects with identical fields will not match.
x = float("nan")
print(x in [x]) # True (same object)
print(float("nan") in [float("nan")]) # False (different objects, NaN != NaN)Where Linear Search Fits
Linear search works on any sequence you can walk through: unsorted arrays, linked lists, lines of a file, or results arriving from a network stream. You do not need to know the length in advance. Every element costs one test, so the work grows with the number of elements the scan visits. The next chapter measures that cost in the best, worst, and average cases. Later chapters show how sorted data lets binary search skip most of those tests.
Exercise
Write find_last_index(items, predicate) that returns the index of the last element for which predicate returns True, or -1 if none does. Then explain why your version can stop early even though it is looking for the "last" match.
Show answer
Scan from the end: for i in range(len(items) - 1, -1, -1): if predicate(items[i]): return i and then return -1 after the loop. Scanning backward makes the last match in list order the first one the loop meets, so returning immediately is correct and avoids checking the elements before it.
Exercise
A teammate writes pos = linear_search(prices, target) and then discount = prices[pos] * 0.1 without checking pos. What happens in Python when target is missing, and what are two ways to fix it?
Show answer
linear_search returns -1, and prices[-1] is the last element, so the code silently computes a discount on the wrong price instead of failing. Fix it by checking if pos != -1: before indexing, or by switching to a convention that cannot be mistaken for a valid index, such as returning None (checked with is not None) or raising an exception the way list.index does.
Exercise
The Java call linearSearch(new Point[]{new Point(1, 2)}, new Point(1, 2)) returns -1 even though the generic method uses Objects.equals. Assuming Point is a user-defined class, what is the likely cause?
Show answer
Point does not override equals (and hashCode), so it inherits Object.equals, which compares references. The two Point objects are distinct, so they are not equal. Overriding equals to compare the coordinates, or declaring Point as a record, fixes it.