Beginner Array Problems Python

Linear Search Program in Python with Output

Find the index of a target in a Python list, or report that it is not found.

  • TimeO(n) worst and average case, O(1) best case
  • SpaceO(1), or O(k) for find_all with k matches
  • Hints3
  • Read2 min
Quick answer

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.

Linear searchfor loop with range and enumerateEarly returnLists
1

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.

Input

A list items and a value target.

Output

"<target> found at index <i>" or "<target> not found".

Examples

Example 1
Inputitems = [12, 45, 7, 30, 9], target = 30
Output30 found at index 3

Index 0 is 12, 1 is 45, 2 is 7, 3 is 30.

Example 2
Inputitems = [12, 45, 7, 30, 9], target = 8
Output8 not found

All five items are checked and none equals 8.

Constraints

  • 0 <= len(items) <= 10^6
  • Items can repeat and be in any order
2

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?
3

Hints

Open one at a time — try again after each.
1 Hint 1
Loop with for i in range(len(items)) so you have the index i.
2 Hint 2
Return i as soon as items[i] == target.
3 Hint 3
Put return -1 after the loop, not in an else inside it.
4

Approach

Reveal the step-by-step approach
  1. For each index i from 0 to len(items) - 1:
  2. If items[i] == target, return i.
  3. 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.

5

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.

6

Solution

Reveal the full Python solution
solution.py
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_all does 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.
  • in returns True or False. list.index(x) returns the first index but raises ValueError if x is missing, so check with in first.

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.

TimeO(n) worst and average case, O(1) best case
SpaceO(1), or O(k) for find_all with k matches
7

Review 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

Practising Python for interviews?

CodeBegun’s Python Full Stack with AI program builds this problem-solving muscle with mentor review and mock interviews.

Chat with us