Python Program to Implement Linear Search

Python Program to Implement Linear Search

Learning how to find a specific element in a dataset is one of the first skills every beginner programmer should master. Linear search is one of the simplest and most intuitive methods for searching. In Python, it allows you to practice working with lists, loops, conditions, and functions while giving immediate results. Even though there are faster search algorithms, linear search is ideal for small datasets and for beginners who want to understand the basics of searching logic.

Pluralsight Logo
Accelerate your tech career
with hands-on learning.
Whether you're a tech newbie or a total pro,
get the skills and confidence to land your next move.
Start 10-Day Free Trial

Linear search is widely used when data is unsorted or when simplicity and readability matter more than speed. It checks each element in order until it finds the one you’re looking for. In this article, we’ll explore multiple ways to implement linear search in Python, including using loops, functions, recursion, and Python’s built-in features. By the end, you’ll have several working examples to experiment with and learn from.

Program 1: Linear Search Using a For Loop

This program shows the simplest way to perform linear search in Python. It checks each element of a list one by one to see if it matches the target value.

numbers = [3, 5, 7, 9, 11, 13]
target = 9
found = False

for i in range(len(numbers)):

    if numbers[i] == target:
        print(f"Element {target} found at index {i}")
        found = True
        break


if not found:
    print(f"Element {target} not found in the list")

Here, the for loop goes through every element of the list, comparing it to the target. If it finds a match, it prints the index and stops searching. This approach is beginner-friendly because it clearly shows how each element is examined sequentially, making it easy to understand how linear search works.

Program 2: Linear Search Using a While Loop

The while loop offers an alternative way to implement linear search. This example demonstrates how to traverse a list using a different loop structure in Python.

numbers = [10, 20, 30, 40, 50]
target = 30
i = 0
found = False

while i < len(numbers):

    if numbers[i] == target:

        print(f"Element {target} found at index {i}")
        found = True
        break

    i += 1


if not found:
    print(f"Element {target} not found in the list")

In this program, the while loop continues as long as the index i is less than the length of the list. Each element is checked until the target is found or the list ends. Using a while loop helps beginners understand different looping constructs and control flow in Python.

Program 3: Linear Search Using a Function

Placing linear search inside a function makes the code reusable and organized. This example demonstrates creating a function to perform the search.

def linear_search(numbers, target):

    for i in range(len(numbers)):

        if numbers[i] == target:
            return i

    return -1  # returns -1 if not found


numbers = [1, 3, 5, 7, 9]
target = 7
result = linear_search(numbers, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

Using a function allows you to reuse the search logic anywhere without repeating code. It also introduces beginners to the concept of returning values from functions and structuring programs in a more organized way.

Program 4: Linear Search Using Recursion

Recursion offers another approach to linear search. Instead of loops, the function calls itself until the target is found or the end of the list is reached.

def linear_search_recursive(numbers, target, index=0):

    if index >= len(numbers):
        return -1
    if numbers[index] == target:
        return index

    return linear_search_recursive(numbers, target, index + 1)


numbers = [2, 4, 6, 8, 10]
target = 6
result = linear_search_recursive(numbers, target)

if result != -1:
    print(f"Element {target} found at index {result}")
else:
    print(f"Element {target} not found in the list")

Recursive linear search teaches a different way of thinking. The function calls itself for the next element until it finds the target or reaches the end of the list. It helps beginners understand recursion and how problems can be solved by breaking them into smaller subproblems.

Program 5: Linear Search Using Python’s in Operator

Python makes linear search extremely simple with its built-in in operator. This method is concise and easy to read.

numbers = [5, 10, 15, 20, 25]
target = 15

if target in numbers:
    index = numbers.index(target)
    print(f"Element {target} found at index {index}")
else:
    print(f"Element {target} not found in the list")

Using in and index makes code cleaner because Python handles the searching internally. It is useful for beginners to see how built-in features can save time while still performing the same task. This approach also introduces Pythonic practices for working with lists efficiently.

Frequently Asked Questions (FAQ)

Linear search is simple but can raise questions for beginners. Here are a few common ones with clear explanations.

Q1: What is linear search used for?
Linear search is used to find a specific element in a list or array. It is most suitable for small or unsorted datasets.

Q2: Is linear search fast?
Linear search is simple but not very efficient for large datasets because it checks each element one by one. Algorithms like binary search are faster for sorted data.

Q3: Can linear search work with strings?
Yes, linear search works with strings, characters, or any data type in a list. The logic remains the same: check each element sequentially.

Q4: Why learn recursion for linear search?
Recursion teaches a different problem-solving approach, strengthens understanding of functions, and helps with more complex programming concepts later.

Q5: Can Python built-in methods replace manual search?
Yes, methods like in and index can perform linear search efficiently, but knowing how to implement it manually helps beginners understand the underlying logic.

Conclusion

Linear search is a fundamental concept that every beginner programmer should understand. By implementing it in Python using loops, functions, recursion, and built-in features, you gain versatile skills for handling data in lists. Each approach has its own benefits, whether it’s simplicity, clarity, or efficiency.

Practicing these programs will make you comfortable with list traversal, conditional statements, and function creation. Start with loops, explore recursion, and then use Python’s built-in features to save time. The more you experiment, the stronger your foundation will be for learning more advanced searching and sorting algorithms in Python.

Scroll to Top