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:

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.   

What is Linear Search in Python? 

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. 

Key Points About Linear Search: 

  • Sequential Checking: The search starts from the first element and moves through the list sequentially. 
  • No Sorting Needed: The data does not need to be sorted. You can perform a linear search on any list or array. 
  • Returns Index: If the element is found, the program returns its index. If not, it typically returns -1 or a message indicating the element is not present. 
  • Simplicity: It is easy to implement using loops or Python’s built-in functions

Linear Search Compared to Other Search Techniques 

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: 

  • Works on any dataset: You don’t need to sort or modify the data. 
  • Easy to understand: Great for beginners who are learning programming logic. 
  • Flexible: Can search for numbers, strings, or any comparable elements. 

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 

How Does the Linear Search Algorithm Work? 

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?" 

  • If the answer is yes, the search is over! The algorithm returns the position (or index) of that element. 
  • If the answer is no, it moves to the next element in the list and asks the same question again. 

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: 

  1. Start: Begin at the first element of the collection (at index 0). 
  2. Compare: Compare the current element with the target value you are searching for. 
  3. Match Found: If the current element matches the target value, the search concludes successfully. Return the index of the current element. 
  4. No Match: If the current element does not match the target value, move to the next element in the sequence. 
  5. Repeat: Continue steps 2 through 4 until you either find the element or have checked every single element in the list. 
  6. End: If you reach the end of the list and haven't found a match, the search concludes unsuccessfully. Return a value (like -1) to signify that the element was not found. 

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. 

  • Step 1: Compare 70 with the first element, 10. No match. 
  • Step 2: Compare 70 with the second element, 50. No match. 
  • Step 3: Compare 70 with the third element, 30. No match. 
  • Step 4: Compare 70 with the fourth element, 70. Match found! The search stops, and we return the index of this element, which is 3. 

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

background

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree17 Months

Placement Assistance

Certification6 Months

Writing Your First Linear Search Program in Python 

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.") 
 

Code Breakdown 

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 

Analyzing Linear Search: Time and Space Complexity 

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 

Time complexity measures how the execution time of an algorithm changes with the size of its input (let's call the input size n). 

  • Best Case: O(1) 

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. 

  • Worst Case: O(n) 

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. 

  • Average Case: O(n) 

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 

Space complexity measures the amount of extra memory the algorithm needs to run, relative to the input size. 

  • Space Complexity: O(1) 

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 

When to Use (and Not Use) Linear Search in Python 

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. 

When to Use Linear Search 

  1. For Small Datasets: If you are working with a list that has only a few dozen or a couple hundred elements, the speed difference between linear search and more complex algorithms is negligible. The simplicity and ease of implementation make it a perfect choice in these cases. 
  2. When the Data is Unsorted: This is the primary advantage of linear search. It makes no assumptions about the order of elements. If your data is not sorted and you cannot or do not want to sort it first (sorting itself takes time), linear search is one of your best options. 
  3. Simplicity is a Priority: In situations where code readability and maintainability are more important than raw performance, the straightforward nature of a program for linear search in python is a huge plus. It's easy for any developer to understand at a glance. 
  4. Checking for a Single Occurrence: If you only need to confirm the presence of an item and don't need to perform frequent searches on the same dataset, the overhead of setting up a more complex search structure isn't justified. 

Also Read: Sorting in Data Structure: Categories & Types [With Examples] 

When to AVOID Linear Search 

  1. For Large Datasets: This is the most significant limitation. If your list contains thousands or millions of elements, iterating through each one can become incredibly slow. Searching for an item at the end of a million-element list would require a million comparisons, which is highly inefficient. 
  2. When Performance is Critical: In applications where search operations must be nearly instantaneous (e.g., database lookups, real-time systems), O(n) time complexity is often unacceptable. 
  3. When the Data is Sorted: If your data is already sorted, you should always use a more efficient algorithm like Binary Search. Binary search repeatedly divides the search interval in half, resulting in a much faster time complexity of O(log n)

Also Read: Learn the Difference Between Linear Search and Binary Search Today! 

Conclusion 

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

Promise we won't spam!

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!

Frequently Asked Questions (FAQs)

1. What is the main disadvantage of a linear search program in python?

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. 

2. Can linear search be used on data types other than numbers?

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. 

3. What happens if the element I'm searching for appears multiple times in the list?

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. 

4. How can I modify the linear search program in python to find all occurrences of an element?

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. 

5. Is linear search a built-in function in Python?

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. 

6. Why is the space complexity of linear search O(1)?

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. 

7. Can I perform a linear search on a dictionary in Python?

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. 

8. Is linear search ever better than binary 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. 

9. What does returning -1 from a linear search function signify?

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. 

10. How does recursion work with linear search?

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. 

11. Does the performance of a linear search python implementation change if the list contains duplicates?

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). 

12. Can you use linear search on a tuple in Python?

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. 

13. What is the alternative name for linear search?

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. 

14. How can I implement a linear search using a while loop instead of a for loop?

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. 

15. Is it possible for a linear search to have a best-case time of O(n)?

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. 

16. How does linear search apply to strings?

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". 

17. What is a sentinel linear search?

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. 

18. Does the linear search algorithm work on a linked list?

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. 

19. Why is understanding a simple linear search program in python important?

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. 

20. Can I improve the average performance of a linear search?

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). 

Rohit Sharma

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

+91

By submitting, I accept the T&C and
Privacy Policy

Start Your Career in Data Science Today

Top Resources

Recommended Programs

upGrad Logo

Certification

3 Months

upGrad
new course

Certification

30 Weeks

Liverpool John Moores University Logo
bestseller

Liverpool John Moores University

MS in Data Science

Double Credentials

Master's Degree

17 Months