Linear Search in Python Program: All You Need to Know
By Rohit Sharma
Updated on Oct 15, 2025 | 14 min read | 8.77K+ views
Share:
For working professionals
For fresh graduates
More
By Rohit Sharma
Updated on Oct 15, 2025 | 14 min read | 8.77K+ views
Share:
Table of Contents
Linear search Program in Python is a simple method to find an element in a list, array, or sequence. It works by checking each item one by one until the desired value is found or the list ends. This approach is straightforward and does not require the data to be sorted. It is often the first search algorithm beginners learn in Python programming.
In this guide, you'll read more about how linear search works in Python, step-by-step programs for different data types, handling multiple occurrences, optimization tips, common mistakes, and practical use cases. We will also compare linear search with other search techniques and answer the most frequently asked questions about writing a program for linear search in Python.
If you're looking to explore more efficient search algorithms and enhance your software engineering expertise, upGrad's Software Engineering course can help you master advanced techniques like Binary Search and more.
Linear search in Python is one of the simplest methods to find a value in a list, array, or sequence. It works by checking each element in order, one by one, until it finds the item you are looking for or reaches the end of the list. Because of its straightforward logic, it is often the first search technique beginners learn when studying Python.
Popular Data Science Programs
Feature |
Linear Search |
Binary Search |
Notes |
Algorithm Type | Sequential | Divide and conquer | Linear search checks elements one by one; binary search splits the list repeatedly |
Data Requirement | No sorting needed | Must be sorted | Binary search requires sorted data; linear search does not |
Time Complexity | O(n) | O(log n) | Linear search can be slower for large lists |
Space Complexity | O(1) | O(1) or O(log n) if recursive | Both efficient in space |
Best Use Case | Small or unsorted lists | Large, sorted datasets | Depends on dataset size and order |
Implementation | Very simple | Slightly complex | Linear search is beginner-friendly |
Duplicates Handling | Returns first occurrence | Can return first or last occurrence with modification | Linear search handles duplicates naturally |
Why Linear Search is Useful:
Even though linear search is not the fastest method for large datasets, its simplicity and reliability make it an important concept to understand. Once you master linear search in Python, you can easily learn other search techniques like binary search or jump search.
Also Read: Everything You Need to Know About Binary Search Tutorial and Algorithm
The core idea behind a linear search is sequential checking. Imagine you have a list of numbers and you're looking for a specific number, say 42. The linear search algorithm starts at the very first element of the list. It asks a simple question: "Is this the number I'm looking for?"
This process repeats sequentially, one element after another, from the beginning to the end of the list. If the algorithm reaches the end of the list without finding the target element, it concludes that the element is not present in the list and typically returns a special value, like -1, to indicate failure.
Let's break this down into a more formal, step-by-step process.
The Linear Search Process:
Also Read: Data Structures & Algorithm in Python: Everything You Need to Know in 2025
Let's visualize this with an example. Suppose we have the list [10, 50, 30, 70, 80, 20] and we want to find the number 70.
This sequential method is why it's called "linear." The path it takes is a straight line from the start to the end of the data. The beauty of this approach lies in its simplicity and the fact that it works perfectly on unsorted data, which is a major advantage over more complex algorithms that require the data to be sorted first. A program of linear search in python is therefore incredibly versatile for simple search tasks.
Data Science Courses to upskill
Explore Data Science Courses for Career Progression
Now that we understand the logic, let's translate it into Python code. Writing a linear search program in python is an excellent exercise for practicing fundamental concepts like functions, loops, and conditional statements. We'll create a reusable function that can search for an element in any given list.
The goal is to write a function that takes two arguments: the list to search through and the target value we want to find. The function should return the index of the target if found, and -1 if not found.
Here is a clean and simple implementation:
Python
def linear_search(data_list, target):
"""
Performs a linear search to find the target value in a list.
Args:
data_list: The list of elements to search through.
target: The value to search for.
Returns:
The index of the target if found, otherwise -1.
"""
for index in range(len(data_list)):
# Compare the current element with the target
if data_list[index] == target:
# If a match is found, return the index immediately
return index
# If the loop completes without finding the target, it's not in the list
return -1
# --- Example Usage ---
# 1. Example where the target is found
my_numbers = [10, 50, 30, 70, 80, 60, 20, 90, 40]
search_target = 70
result = linear_search(my_numbers, search_target)
if result != -1:
print(f"Target {search_target} found at index: {result}")
else:
print(f"Target {search_target} not found in the list.")
# 2. Example where the target is NOT found
search_target_2 = 100
result_2 = linear_search(my_numbers, search_target_2)
if result_2 != -1:
print(f"Target {search_target_2} found at index: {result_2}")
else:
print(f"Target {search_target_2} not found in the list.")
Let's dissect the program for linear search in python piece by piece to ensure everything is crystal clear.
Code Snippet | Explanation |
def linear_search(data_list, target): | This defines our function named linear_search. It accepts two parameters: data_list (the list we'll search) and target (the item we're looking for). |
for index in range(len(data_list)): | This is the heart of the search. We use a for loop to iterate through the list. len(data_list) gets the total number of items, and range() generates a sequence of numbers from 0 up to (but not including) that total. The index variable will hold the current position (0, 1, 2, etc.) in each iteration. |
if data_list[index] == target: | Inside the loop, this if statement does the comparison. data_list[index] accesses the element at the current position. We check if it is equal (==) to our target. |
return index | If the if condition is true (we found a match!), the function immediately stops and sends back the current index. The return statement exits the function entirely. |
return -1 | This line is crucial. It is placed outside the for loop. If the loop finishes without ever finding the target, it means the return index line was never executed. The code then proceeds to this line, returning -1 to signal that the search was unsuccessful. |
This structure is efficient because it stops as soon as the element is found, saving unnecessary checks. This simple yet effective structure is why the linear search python implementation is a favorite for introductory programming courses.
Also Read: Python Recursive Function Concept: Python Tutorial for Beginners
Understanding an algorithm's performance is as important as knowing how to write it. In computer science, we use "Big O notation" to describe an algorithm's efficiency. This notation tells us how the runtime or memory usage grows as the input size grows. For a linear search program in python, the analysis is very straightforward.
Time complexity measures how the execution time of an algorithm changes with the size of its input (let's call the input size n).
The best-case scenario happens when the element you are looking for is the very first element in the list. The loop runs only once, compares the first element, finds a match, and returns immediately. The time taken is constant, regardless of how large the list is. This is denoted as O(1), which means constant time.
The worst-case scenario occurs when the target element is the last element in the list, or if the element is not in the list at all. In both situations, the algorithm must iterate through all n elements to reach its conclusion. Therefore, the runtime grows linearly with the number of elements in the list. This is denoted as O(n), which means linear time.
On average, assuming the element could be at any position with equal probability, you would expect to search through about half the list (n/2). In Big O notation, we drop constant factors (like 1/2), so the average case is also considered O(n). The runtime still scales linearly with the input size.
Also Read: Time Complexity Explained: Why It Matters in Algorithm Design?
Space complexity measures the amount of extra memory the algorithm needs to run, relative to the input size.
The linear search program in python is very memory-efficient. It only needs a few variables to store the index and the target value. The amount of memory it uses does not increase as the list gets larger. Whether you search a list of 10 items or 10 million items, the extra memory required is the same. This is known as constant space complexity, or O(1).
Here's a summary table for quick reference:
Complexity Type | Best Case | Average Case | Worst Case |
Time Complexity | O(1) | O(n) | O(n) |
Space Complexity | O(1) | O(1) | O(1) |
This analysis reveals the main trade-off of linear search: it's simple to implement but can be slow on large datasets. Understanding this is key to deciding when a linear search python solution is appropriate.
Also Read: Time and Space Complexity in Data Structures: A Detailed Guide
While it's a fundamental algorithm, a linear search program in python isn't always the best choice. Knowing its strengths and weaknesses will help you decide when to use it and when to look for a more efficient alternative.
Also Read: Sorting in Data Structure: Categories & Types [With Examples]
Also Read: Learn the Difference Between Linear Search and Binary Search Today!
The linear search program in python is a cornerstone of search algorithms. Its strength lies in its simplicity, adaptability to unsorted data, and minimal memory usage. We've explored its step-by-step logic, translated that logic into a clean Python function, and analyzed its performance to understand its O(n) time complexity. We also clarified its ideal use cases—small or unsorted datasets where simplicity outweighs the need for blazing-fast speed.
By mastering this algorithm, you've built a solid foundation. You now understand the trade-offs between simplicity and efficiency, which will guide you as you learn more advanced algorithms like binary search. Keep this fundamental tool in your programming toolkit; it's a reliable and practical solution for many everyday coding challenges.
Unlock the power of data with our popular Data Science courses, designed to make you proficient in analytics, machine learning, and big data!
Subscribe to upGrad's Newsletter
Join thousands of learners who receive useful tips
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!
The main disadvantage is its time complexity of O(n), which means its performance degrades linearly as the size of the dataset increases. This makes it inefficient and slow for searching in large lists or arrays.
Absolutely. A program of linear search in python can be used on a list of any data type that supports the equality comparison (==), including strings, booleans, or even complex objects, as long as you can define what makes two objects equal.
The standard implementation of a linear search will find and return the index of the first occurrence of the element. Once it finds a match, it immediately stops searching and returns that index.
Instead of returning immediately after finding a match, you can initialize an empty list to store indices. Then, you would loop through the entire list, and every time you find a match, you append its index to your list of indices. Finally, you return the list of all found indices.
While Python doesn't have a function explicitly named linear_search(), the underlying principle is used in common operations. For example, the in operator (e.g., if target in my_list:) and the .index() method (e.g., my_list.index(target)) perform a linear search behind the scenes.
The space complexity is O(1) or "constant" because the amount of extra memory the algorithm requires does not depend on the size of the input list. It only uses a few fixed-size variables (like one for the loop index), regardless of whether the list has 10 elements or 10 million.
You can perform a linear search on a dictionary's keys, values, or items. For instance, target in my_dict.keys() performs a linear search on the keys (though dictionary key lookups are typically much faster, O(1) on average). Searching through .values() or .items() would be a classic linear search.
Yes, linear search is better than binary search in two key scenarios: when the data is unsorted, and for very small datasets. Binary search requires sorted data, and the overhead of sorting the data first can make linear search faster for small or unsorted lists.
Returning -1 is a conventional way to indicate that the search was completed, but the target element was not found in the list. Since list indices are always non-negative (0 or greater), -1 serves as a safe and clear signal of failure.
A linear search can be implemented recursively. A recursive function would check the first element of the list. If it's a match, it returns the index. If not, it calls itself on the rest of the list (from the second element onwards), adding one to the result to adjust the index.
The performance depends on the position of the first occurrence of the target. If the first duplicate is near the beginning of the list, the search will be fast (best case). If all duplicates are near the end, the search will be slow (worst case).
Yes, the exact same linear search program in python logic works for tuples as well. Since tuples are ordered, iterable collections, you can loop through them sequentially and compare elements just as you would with a list.
Linear search is also commonly known as sequential search. This name highlights the core mechanism of the algorithm, which involves checking each element in sequence until a match is found.
You can use a while loop by initializing an index variable to 0. The loop would continue as long as the index is less than the length of the list. Inside the loop, you check for a match and, if none is found, you manually increment the index.
No, the best-case time complexity is always O(1). The only way the algorithm would have to check all n elements in the best possible scenario is if that scenario was defined as finding the last element, which is typically considered the worst case.
You can use linear search to find a character within a string. Since strings are iterable sequences of characters, the same looping logic applies. For example, you can write a program of linear search in python to find the first index of the character 'p' in the string "apple".
A sentinel linear search is a slight optimization of the standard algorithm. It involves adding the target element to the end of the list before starting the search. This guarantees the element will be found, eliminating the need to check for the end of the list in every iteration, which can slightly reduce the number of comparisons inside the loop.
Yes, linear search is a very natural fit for linked lists. Since you can only access elements of a linked list sequentially by traversing from the head node, the one-by-one checking process of linear search is the standard way to find an element in one.
It's important because it teaches fundamental programming concepts: iteration, comparison, and conditional logic. It also serves as a baseline for understanding algorithm performance (complexity analysis) and appreciating why more advanced algorithms are necessary for larger datasets.
The average performance is intrinsically tied to its O(n) nature, so you can't change its fundamental complexity. However, if you know that some elements are searched for more frequently, you could improve practical performance by moving found elements to the front of the list, making subsequent searches for them O(1).
834 articles published
Rohit Sharma is the Head of Revenue & Programs (International), with over 8 years of experience in business analytics, EdTech, and program management. He holds an M.Tech from IIT Delhi and specializes...
Speak with Data Science Expert
By submitting, I accept the T&C and
Privacy Policy
Start Your Career in Data Science Today
Top Resources