Python Algorithms

Linear Search in Python

Linear search examines values from left to right and works even when the input is not sorted.

What is linear search?

Linear search checks each item from the beginning until it finds the target or reaches the end. The data does not need to be sorted first.

How the algorithm works

  1. Start at index 0.
  2. Compare the current item with the target.
  3. Return its index when equal; otherwise continue.
  4. Return -1 after the final item when no match exists.
Complexity: O(n) average/worst-case time and O(1) extra space.

Linear Search in Python visualizer

O(n)

Use Play or Step to follow each comparison and data movement.

Example code

Run code →
main.py
def linear_search(values, target):
    for index, value in enumerate(values):
        if value == target:
            return index
    return -1

print(linear_search([14, 3, 27, 8, 19], 8))

Expected output

3

How it works

Enumerate provides each index and value. The search returns immediately when it finds the target. Worst-case time complexity is O(n).

Change the values and run the program in the CodeUtility online Python compiler without installing Python locally.

Practice exercises

Modify the runnable example with the exercises below to build understanding beyond copying the result.

  1. Try empty, single-item, and duplicate-value inputs.
  2. Print state after every step to observe the algorithm.
  3. Benchmark 100, 1,000, and 10,000 items, then compare another approach.
Run in Python IDE →