Linear Search
in Python
Learn how to search through a list one element at a time, understand its time complexity, and implement it from scratch in Python.
What Is Searching?
Searching is one of the most fundamental operations in computer science. Given a collection of data (like a Python list), searching means finding whether a specific target value exists in that collection, and if so, where it is located.
Meet Linear Search
Linear search (also called sequential search) is the simplest search algorithm. It checks every element in the list one by one, from the first element to the last, until it finds the target or runs out of elements.
How It Works Visually
Searching for the value 7 in the list [3, 8, 1, 7, 5]. We check each element left to right:
The Algorithm
Time Complexity
Linear vs Binary Search
| Linear Search | Binary Search | |
|---|---|---|
| Requires sorted list? | No | Yes |
| Time complexity | \( O(n) \) | \( O(\log n) \) |
| Strategy | Check every element | Divide and conquer |
| Simplicity | Very simple | More complex |
| Best for | Small / unsorted lists | Large sorted lists |
How to Implement It
for i in range(len(lst)) to visit each element.if lst[i] == target.return i.Basic Implementation
Example 1: Target Found
Example 2: Target Not Found
Example 3: Searching Strings
Linear search is not limited to numbers. It works on any data type that supports equality comparison (==).
Pythonic Variation
Python's enumerate() function gives you both the index and the value in each loop iteration, making the code cleaner:
Return Index vs Boolean
Sometimes you only need to know if the target exists, not where. Here are both patterns:
True / False. Use when you only need existence.Common Mistakes
return -1 inside the loop causes it to return after the first non-match instead of checking all elements.is instead of ==: is checks identity (same object), not equality (same value).range(1, len(lst)) skips index 0, missing the first element entirely.Summary
| Property | Linear Search |
|---|---|
| Strategy | Check each element sequentially |
| Input requirement | Any list (sorted or unsorted) |
| Best case | \( O(1) \) |
| Worst / Average case | \( O(n) \) |
| Space complexity | \( O(1) \) |
| Returns | Index of target, or \( -1 \) |
| Works on | Numbers, strings, any comparable type |
Question 1 of 5
What is the worst-case time complexity of linear search on a list of \( n \) elements?
Question 2 of 5
What does this function return?
Question 3 of 5
What is wrong with this code?
else block within the loop. If the first element doesn't match, the function immediately returns \( -1 \) without checking the rest of the list. The fix: move return -1 outside the loop.Question 4 of 5
Which of the following is true about linear search?
Question 5 of 5
How many comparisons does linear search make to find 42 in [10, 42, 7, 3]?