Linear Search Program in Python with Output
Find the index of a target in a Python list, or report that it is not found.
- Time
O(n) worst and average case, O(1) best case - Space
O(1), or O(k) for find_all with k matches - Hints3
- Read2 min
Linear search in Python checks each element of a list from index 0. When an element equals the target, return its index at once. If the loop finishes without a match, return -1. It works on unsorted lists, takes O(n) time in the worst case and O(1) extra space. Python's built-in "x in list" and list.index(x) use the same idea.
Problem statement
Write a linear search program in Python. Given a list and a target value, return
the index of the first match, or -1 if the target is not in the list. Print a clear
message for both cases.
The list does not need to be sorted. That is the main difference from binary search.
A list items and a value target.
"<target> found at index <i>" or "<target> not found".
Examples
items = [12, 45, 7, 30, 9], target = 3030 found at index 3Index 0 is 12, 1 is 45, 2 is 7, 3 is 30.
items = [12, 45, 7, 30, 9], target = 88 not foundAll five items are checked and none equals 8.
Constraints
- 0 <= len(items) <= 10^6
- Items can repeat and be in any order
Think before you code
Reveal the questions to ask yourself first
- You need to return a position. How do you loop with the index?
- Can you stop as soon as you find the target?
- At which point are you sure the target is missing?
Hints
Open one at a time — try again after each.1 Hint 1
2 Hint 2
3 Hint 3
Approach
Reveal the step-by-step approach
- For each index
ifrom 0 tolen(items) - 1: - If
items[i] == target, returni. - After the loop, return
-1.
Returning -1 is a common way to say "not found", because no real index is negative
in this function. The caller checks for -1 and prints the right message.
| Case | Comparisons for n items |
|---|---|
| Best: target at index 0 | 1 |
| Worst: target last or missing | n |
| Average, target present | about n / 2 |
If the list is sorted and large, binary search needs far fewer comparisons.
Dry run
Walk through the example step by step
items = [12, 45, 7, 30, 9], target = 30:
i | items[i] | equal to 30?
--+----------+-------------
0 | 12 | no
1 | 45 | no
2 | 7 | no
3 | 30 | yes, return 3
For target = 8, all five rows say "no", the loop ends, and the function returns -1.
Solution
Reveal the full Python solution
def linear_search(items, target):
for i in range(len(items)):
if items[i] == target:
return i
return -1
numbers = [12, 45, 7, 30, 9]
for target in [30, 12, 8]:
index = linear_search(numbers, target)
if index != -1:
print(target, "found at index", index)
else:
print(target, "not found")Output:
30 found at index 3
12 found at index 0
8 not found
12 is found on the first comparison, the best case. 8 needs all five comparisons, the worst case.
Search program in Python with user input
enumerate() gives the index and the value together. Users usually count from 1, so
this version prints the position i + 1.
items = list(map(int, input("Enter numbers: ").split()))
target = int(input("Enter number to search: "))
found = False
for i, value in enumerate(items):
if value == target:
print("Found at position", i + 1)
found = True
break
if not found:
print("Not found")
Enter numbers: 5 8 3 9 1
Enter number to search: 9
Found at position 4
Enter numbers: 5 8 3
Enter number to search: 4
Not found
Find all positions, strings, and built-in shortcuts
def find_all(items, target):
positions = []
for i in range(len(items)):
if items[i] == target:
positions.append(i)
return positions
print(find_all([4, 2, 4, 9, 4], 4))
print(find_all(["apple", "mango", "kiwi"], "mango"))
print(find_all([1, 2, 3], 5))
nums = [12, 45, 7]
print(45 in nums, nums.index(45))
[0, 2, 4]
[1]
[]
True 1
find_alldoes not stop at the first match, so it always checks every item.- The same code works for a list of strings, because
==compares strings too. inreturns True or False.list.index(x)returns the first index but raisesValueErrorifxis missing, so check withinfirst.
The Java version is on linear search in Java. To sort a list before searching, see selection sort in C for the logic. More list practice: Python list comprehension.
O(n) worst and average case, O(1) best caseO(1), or O(k) for find_all with k matchesReview before the interview
Common mistakes
- Writing else: return -1 inside the loop, so only the first item is ever checked.
- Printing "not found" inside the loop, once for every item that does not match.
- Calling list.index(x) without checking, which raises ValueError when x is missing.
- Comparing the number 5 with the string "5". input() returns a string, so convert with int() first.
Edge cases to test
- Empty list: the loop does not run and the function returns -1.
- Duplicates: the function returns the first index only.
- Target at the last index is the slowest case that still finds it.
- Mixed types: 1 == 1.0 is True in Python, so searching for 1 also matches 1.0.
Interview follow-ups
- How would you return the last index of the target instead of the first?
- How would you write linear search with a while loop?
- When is binary search better than linear search?
Keep practising
Linear Search in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemBinary Search in Java: Program and Logic
Hints · Dry run · SolutionSolve Similar problemFind the Largest Element in an Array
Hints · Dry run · SolutionSolve Similar problemCount the Frequency of Each Element in an Array
Hints · Dry run · SolutionSolve Related learningWhat Is An Array
TutorialLearn Related learningPython List Comprehension
TutorialLearn Related learningPython Interview Questions
TutorialLearn CareerPilot AIPractice under pressure
Take an AI mock interview and get question-by-question feedback.
Mock interviewStartPractising Python for interviews?
CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.
