Editor

Linear search in Python

Linear search checks the values one by one, from the first to the last, until it finds the one it wants. It works on any list, sorted or not.

The arrow keys step through it. Edit the code to try your own input.

How it works

  1. Start at index 0 and compare nums[i] with target.
  2. If they are equal, return i straight away.
  3. Otherwise move i one step right and compare again.
  4. If the loop ends without a match, the value is not in the list, so the function returns -1.

What to watch

  • Watch i stop at 4 when searching for 9, because that is where the match is.
  • Watch the search for 7 visit every bar before it gives up and returns -1.
  • Watch the bars: they are not sorted, and linear search does not need them to be.

The code

def linear_search(nums, target):
    for i in range(len(nums)):
        if nums[i] == target:
            return i          # found it: stop at once
    return -1                 # checked every value: not there

data = [8, 3, 12, 5, 9, 1]
print("Index of 9:", linear_search(data, 9))
print("Index of 7:", linear_search(data, 7))
Output
Index of 9: 4
Index of 7: -1

Open it in the editor · Python Program to Search for an Element in a List, explained