Linear Search in Python Program: All You Need to Know
By Rohit Sharma
Updated on Jan 31, 2025 | 14 min read | 8.2k views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Jan 31, 2025 | 14 min read | 8.2k views
Share:
Table of Contents
A linear search in Python program is a simple yet powerful algorithm used to find an element in a list by checking each item sequentially. The linear search algorithm is crucial for beginners learning Python and data structures.
In this blog, you will dive into the concept of linear search, how to implement it in Python, and explore different variations of the program to enhance your understanding.
Linear search is a straightforward algorithm used to find an element in a list by checking each item one by one, starting from the beginning. It moves through the list sequentially until it finds the target element or reaches the end of the list.
This method works well for unsorted data because it doesn't require any order in the list. It’s especially useful when you are dealing with small datasets or when a simple solution is needed for finding elements.
For example, if you need to find a missing student ID in an unsorted database, linear search is ideal as it allows you to quickly iterate through the entries without needing sorting or complex algorithms.
In Python, implementing the linear search algorithm is easy and practical, especially when efficiency is not the top priority. You can use this technique to search for specific values in a variety of real-world applications, like finding a name in an unsorted list of contacts.
Different search algorithms offer varying advantages based on the dataset's size and structure; understanding these differences will help you in choosing the most efficient approach.
Here’s a comparison of Linear Search with other popular search algorithms:
Search Algorithm |
Time Complexity |
Space Complexity |
Best For |
Linear Search | O(n) | O(1) | Quick searches on small or unsorted datasets |
Binary Search | O(log n) | O(1) | Fast searches in large datasets where data is sorted |
Jump Search | O(√n) | O(1) | Faster than linear search for moderately sorted datasets |
Interpolation Search | O(log log n) | O(1) | Fast searches in datasets with uniform distribution |
In this comparison, Linear Search is simple but not the most efficient for larger datasets, especially when compared to Binary Search or more advanced algorithms like Jump Search and Interpolation Search.
Also Read: Linear Search vs Binary Search: Key Differences Explained Simply
Now that you understand how linear search works, let’s dive into the practical steps to implement the linear search algorithm in Python.
To perform a linear search in Python, you need to check each element of the list one by one until you find the target. The process is simple:
Here’s an example to help you understand how it works:
def linear_search(arr, target):
for index in range(len(arr)):
if arr[index] == target:
return index # Return the index if found
return -1 # Return -1 if the element is not found
# Example usage:
numbers = [10, 20, 30, 40, 50]
target = 30
result = linear_search(numbers, target)
print(f"Element {target} found at index: {result}")
Output:
Element 30 found at index: 2
Explanation:
This simple linear search technique works well for small or unsorted lists.
Next, let's explore Python programs for linear search, covering various methods to implement and enhance your understanding of the algorithm.
In this section, you'll explore various Python implementations of linear search, each tailored to different use cases and methods for better understanding and optimization.
In this example, we will implement a simple linear search in a Python program using an iterative approach. This approach is easy to understand and is ideal for beginners. The program will search for an element in a list by checking each item one by one.
def linear_search(arr, target):
# Iterate through the list
for i in range(len(arr)):
if arr[i] == target:
return i # Element found, return index
return -1 # Element not found
# Example usage
arr = [5, 2, 9, 1, 5, 6]
target = 9
result = linear_search(arr, target)
# Output result
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found.")
Output:
Element 9 found at index 2
Explanation:
While Linear Search is straightforward and effective for many cases, there are several edge cases that may arise during its implementation.
Let’s explore some common edge cases for the given Python program:
Also Read: Selection Sort Algorithm in Data Structure: Code, Function & Example
This approach is straightforward and well-suited for small datasets or when data is unsorted.
This method involves looping through the array one element at a time, comparing each element to the target, and returning the index when the element is found.
def linear_search_iterative(arr, target):
for i in range(len(arr)): # Iterate through the array
if arr[i] == target: # If the element matches
return i # Return the index of the element
return -1 # Return -1 if the element is not found
# Example usage
arr = [12, 34, 54, 2, 3]
target = 54
result = linear_search_iterative(arr, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found.")
Output:
Element 54 found at index 2
Explanation:
The Iterative Linear Search method is useful for searching through an array element by element, and it handles various edge cases well. However, it's important to consider some specific scenarios that may affect its behavior.
Let’s explore the common edge cases for this implementation:
This approach is useful for its simplicity and effectiveness, especially when dealing with small or unsorted datasets.
The linear search using a recursive approach will repeatedly call itself until the element is found or the end of the list is reached.
def linear_search_recursive(arr, target, index=0):
# Base case: if we've checked all elements
if index == len(arr):
return -1
if arr[index] == target: # If the element matches
return index
return linear_search_recursive(arr, target, index + 1) # Recursive call
# Example usage
arr = [5, 3, 7, 2, 9]
target = 7
result = linear_search_recursive(arr, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found.")
Output:
Element 7 found at index 2
Explanation:
This approach provides a more elegant, recursive solution but may not be as efficient as the iterative approach for large datasets due to stack depth.
The recursive approach to linear search can handle several edge cases effectively. However, there are some situations where special attention is needed:
Also Read: Tower of Hanoi Algorithm Using Recursion: Definition, Use-cases, Advantages
This method is particularly helpful when searching for string patterns or substrings, making it an interesting variation of the traditional linear search.
import re
def linear_search_regex(arr, target):
pattern = re.compile(re.escape(str(target))) # Create a RegEx pattern
for i, item in enumerate(arr):
if pattern.search(str(item)): # Search for the pattern in the item
return i # Return index if match is found
return -1 # Return -1 if not found
# Example usage
arr = ['apple', 'banana', 'cherry', 'date']
target = 'cherry'
result = linear_search_regex(arr, target)
if result != -1:
print(f"Element {target} found at index {result}")
else:
print(f"Element {target} not found.")
Output:
Element cherry found at index 2
Explanation:
The RegEx method of linear search is useful for searching string patterns and substrings, but there are several edge cases to consider:
To further enhance your Python skills, upGrad offers tailored programs designed to take your expertise to the next level.
upGrad’s Python and programming-related courses offer a hands-on approach to mastering key algorithms like linear search. These programs deepen your understanding of data manipulation and algorithmic thinking, providing you with real-world applications.
Here are some of the top courses you can check out:
Start with upGrad's free courses to build a solid Python foundation, and unlock advanced opportunities in data science and AI.
For personalized career guidance, consult upGrad’s expert counselors or visit our offline centers to find the best course tailored to your goals.
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Elevate your career by learning essential Data Science skills such as statistical modeling, big data processing, predictive analytics, and SQL!
Stay informed and inspired with our popular Data Science articles, offering expert insights, trends, and practical tips for aspiring data professionals!
Get Free Consultation
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources