Python Linear Search


Linear search is the simplest searching technique in programming. It checks each element in a list one by one until it finds the value you want. Even though it’s not the fastest method, it’s reliable, easy to understand and works on any type of list. You don’t need the list to be sorted, and you don’t need any special conditions. Because of this, linear search is often the first search algorithm beginners learn before moving to faster ones like binary search.

In this tutorial, you’ll understand how linear search works, why it’s useful, how to write it in Python, the step-by-step flow behind the algorithm and several practical examples. You’ll also learn when you should and shouldn’t use this method in real-world programs.

What Is Linear Search?

Linear search is a technique where you scan each item in a list from start to end. You compare every element with the target value. If you find a match, you return the position. If not, you reach the end of the list and conclude that the value doesn’t exist.

This method follows a simple idea:

  1. Start from the first index.

  2. Compare the value with the target.

  3. If they match, return the index.

  4. If not, move to the next element.

  5. Stop when you reach the end.

This makes linear search easy to write and easy to visualize.

Why Use Linear Search?

Linear search is useful because:

  • It works on any list, sorted or unsorted.

  • It handles small datasets well.

  • It is simple to implement.

  • It works with numbers, strings and objects.

  • It is predictable and easy to debug.

You don’t need to prepare or pre-process data before searching. That makes it perfect for quick checks or small inputs.

How Linear Search Works Internally

Think of a list of names:

["Sara", "Mia", "Lara", "Nina"]

If you want to find "Lara", the search goes like this:

  • Check "Sara" → not a match

  • Check "Mia" → not a match

  • Check "Lara" → match found at index 2

The algorithm ends immediately when it finds the value. If the target was not present, it would check all elements before stopping.

Python Code for Linear Search

A simple implementation looks like this:

def linear_search(data, target):
    for index in range(len(data)):
        if data[index] == target:
            return index
    return -1

If the element is found, the index is returned. If not, the function returns -1 to indicate failure.

You can also write a version using direct iteration:

def linear_search(data, target):
    for i, value in enumerate(data):
        if value == target:
            return i
    return -1

Both versions follow the same logic.

Example Usage

numbers = [10, 25, 37, 42, 55]
result = linear_search(numbers, 42)

if result != -1:
    print("Found at index:", result)
else:
    print("Not found")

Output:

Found at index: 3

Time Complexity of Linear Search

Linear search has:

  • Best case: O(1) (first element matches)

  • Worst case: O(n) (last element or not present)

  • Average case: O(n)

This means the time increases with the size of the list. That’s why it’s not suitable for huge datasets.

When Linear Search Is a Good Choice

Linear search works well when:

  • The list is small.

  • Data is not sorted.

  • You only search occasionally.

  • You want a quick and simple solution.

  • Memory is limited and you don’t want extra structures.

It is also helpful when dealing with strings, objects or mixed data types.

When Linear Search Is Not Recommended

Avoid linear search when:

  • The list is very large.

  • You need frequent searches.

  • Data is already sorted.

  • Performance is important.

In such cases, algorithms like binary search or hash maps give faster results.

Real-Life Uses of Linear Search

Searching a contact name manually

You look through names one by one until you find the right one.

Scanning options in a settings page

The app checks each label until the right match appears.

Checking for a file in a small folder

You scroll through items until you see the correct file.

Validating user input

You compare input with a list of allowed values.

Linear search appears in places where the data size is small or convenience matters more than speed.

Step-by-Step Example

List:

[3, 8, 12, 15, 20]

Target: 15

Steps:

  1. Compare 3 with 15 → no

  2. Compare 8 with 15 → no

  3. Compare 12 with 15 → no

  4. Compare 15 with 15 → match at index 3

  5. Stop searching

The algorithm never checks 20 because it already found the result.

Practical Examples

Example 1: Search string in a list

names = ["Diya", "Mia", "Lara"]
print(linear_search(names, "Lara"))

Example 2: Search number in mixed list

data = [4, "apple", 9, "banana"]
print(linear_search(data, "banana"))

Example 3: Search in user input list

items = input().split()
print(linear_search(items, "yes"))

Example 4: Search for minimum match

values = [15, 40, 60]
print(linear_search(values, 15))

Example 5: Search for last element

print(linear_search(values, 60))

Example 6: Element not found

print(linear_search(values, 99))

Example 7: Case-sensitive search

words = ["Cat", "dog", "Lion"]
print(linear_search(words, "cat"))

Example 8: Search inside nested list

nested = [[1,2], [3,4]]
print(linear_search(nested, [3,4]))

Example 9: Custom object search

class Item:
    def __init__(self, code):
        self.code = code

items = [Item(1), Item(2)]
print(linear_search([i.code for i in items], 2))

Example 10: Searching in real-time input

numbers = list(map(int, input().split()))
print(linear_search(numbers, 5))

Summary of the Tutorial

Linear search is a simple and beginner-friendly method for finding a value inside a list. It checks each element from start to finish and stops when a match is found. You learned how the algorithm works, how to implement it, when it’s helpful and when it’s not ideal. Even though it’s slow for large datasets, it’s perfect for small lists or quick checks. Understanding linear search gives you a strong starting point before learning faster algorithms like binary search.


Practice Questions

Q1. Write a Python program to search for number 25 in a list of 10 elements using linear search.

Q2. Write a Python program to modify the search function to return True or False instead of the index.

Q3. Write a Python program to perform linear search in a list of strings.

Q4. Write a Python program to handle the case where the target occurs more than once and return all indices.

Q5. Write a Python program to modify the search function to print the number of comparisons made.

Q6. Write a Python program to accept a list and a target value from the user and search for that value.

Q7. Write a Python program to return the last occurrence of the target element in the list.

Q8. Write a Python program to search for a number in a nested list (list of lists).

Q9. Write a Python program to check if a value is present in a list of dictionaries by a specific key.

Q10. Write a Python program to implement linear search without using range() or index values – iterate directly through elements.


Go Back Top