Python Program for Linear Search with Example and Explanation
for loop and if condition to find the target value; for example, for i in range(len(arr)): if arr[i] == target: return i.Examples
How to Think About It
Algorithm
Code
def linear_search(arr, target): for i in range(len(arr)): if arr[i] == target: return i return -1 # Example usage arr = [5, 3, 7, 1, 9] target = 7 result = linear_search(arr, target) print(result)
Dry Run
Let's trace the example where arr = [5, 3, 7, 1, 9] and target = 7 through the code.
Start loop at index 0
Check if arr[0] (5) == 7 → No
Move to index 1
Check if arr[1] (3) == 7 → No
Move to index 2
Check if arr[2] (7) == 7 → Yes, return 2
| Index | Value | Target | Match? |
|---|---|---|---|
| 0 | 5 | 7 | No |
| 1 | 3 | 7 | No |
| 2 | 7 | 7 | Yes |
Why This Works
Step 1: Loop through each element
The for loop goes through each item in the list one by one to check for the target.
Step 2: Compare current element with target
The if statement compares the current element to the target value to find a match.
Step 3: Return index if found
If a match is found, the function returns the current index immediately to stop searching.
Step 4: Return -1 if not found
If the loop finishes without finding the target, the function returns -1 to indicate absence.
Alternative Approaches
def linear_search_while(arr, target): i = 0 while i < len(arr): if arr[i] == target: return i i += 1 return -1 print(linear_search_while([5,3,7,1,9],7))
def linear_search_try(arr, target): try: return arr.index(target) except ValueError: return -1 print(linear_search_try([5,3,7,1,9],7))
Complexity: O(n) time, O(1) space
Time Complexity
The search checks each element once, so time grows linearly with list size, making it O(n).
Space Complexity
No extra space is used besides variables, so space complexity is O(1).
Which Approach is Fastest?
All linear search methods have similar speed; using built-in index() is concise but may raise exceptions.
| Approach | Time | Space | Best For |
|---|---|---|---|
| For loop linear search | O(n) | O(1) | Clear step-by-step search |
| While loop linear search | O(n) | O(1) | Alternative loop style |
| Built-in index() with try-except | O(n) | O(1) | Concise code, handles errors |