Last modified: Aug 14, 2026

Python Array Search: Linear vs Binary

Searching for an item in an array is a core task. Python offers two main approaches: linear search and binary search. Each has its strengths and weaknesses. Understanding them helps you write faster and more efficient code.

This guide breaks down both methods. You will learn how they work, see code examples, and understand when to use each. We will focus on clarity and practical use.

What is Linear Search?

Linear search is the simplest method. It checks each element in the array one by one. It starts from the first item and moves to the last until it finds a match. This method does not require the array to be sorted.

Think of it like looking for a book on a shelf. You start at one end and scan every book until you find the one you need. This is straightforward and works for any list. It is the default approach when you use Python's in operator or the list.index() method.

Linear Search Example

Here is a simple implementation of linear search in Python. We will create a function that returns the index of the target value, or -1 if not found.


def linear_search(arr, target):
    """Find the target in arr. Return index or -1."""
    for i in range(len(arr)):
        if arr[i] == target:
            return i  # Found, return the index
    return -1  # Not found

# Example usage
numbers = [5, 3, 8, 1, 9, 2]
target = 8
result = linear_search(numbers, target)

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

Found 8 at index 2.

This code loops through each element. It compares the current element to the target. If they match, it returns the index. If the loop finishes without a match, it returns -1. This is clean and easy to understand.

Linear search is perfect for small arrays. It is also useful when your data is unsorted. For larger datasets, it can become slow. The worst-case scenario is checking every single element. This gives a time complexity of O(n), where n is the number of elements.

What is Binary Search?

Binary search is a much faster algorithm. However, it has a strict requirement: the array must be sorted. It works by repeatedly dividing the search interval in half. This is like looking up a word in a dictionary. You open the book to the middle and decide if your word comes before or after that page.

The algorithm starts by comparing the target to the middle element. If they are equal, the search is done. If the target is smaller, you search the left half. If it is larger, you search the right half. This process repeats until you find the target or the interval is empty.

This method drastically reduces the number of comparisons. Each step eliminates half of the remaining elements. This results in a time complexity of O(log n). For large arrays, this is exponentially faster than linear search.

Binary Search Example

Here is a classic iterative implementation of binary search. We will use two pointers, low and high, to track the search area.


def binary_search(arr, target):
    """Find target in sorted arr. Return index or -1."""
    low = 0
    high = len(arr) - 1

    while low <= high:
        mid = (low + high) // 2  # Integer division for the middle
        if arr[mid] == target:
            return mid  # Target found
        elif arr[mid] < target:
            low = mid + 1  # Search in the right half
        else:
            high = mid - 1  # Search in the left half
    return -1  # Target not found

# Example usage with a sorted array
sorted_numbers = [1, 2, 3, 5, 8, 9]
target = 5
result = binary_search(sorted_numbers, target)

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

Found 5 at index 3.

Notice how the array is sorted. The code calculates the middle index. It then compares the middle value to the target. Based on the comparison, it narrows the search range. This loop continues until the target is found or the range is empty.

Binary search is incredibly efficient. It is the go-to choice for searching in sorted data. Remember that sorting the array first adds a cost. If you only search once, sorting plus binary search might be slower than a single linear search.

Key Differences: Linear vs Binary

The core difference lies in their prerequisites and speed. Linear search works on any array. Binary search requires a sorted array. This single fact dictates when to use each.

Performance is another major difference. Linear search has a time complexity of O(n). Binary search has O(log n). For an array of 1 million elements, linear search might take 1 million steps. Binary search would take about 20 steps. That is a massive difference.

Space complexity is similar. Both algorithms can be implemented with constant extra space. Binary search, however, can be recursive, which uses stack space. The iterative version we showed uses O(1) space.

When to Use Which Search?

Choosing the right algorithm depends on your specific situation. Here is a simple guide to help you decide.

Use linear search when:

  • Your array is small or unsorted.
  • You are searching only once.
  • Simplicity is more important than speed.
  • You are working with a linked list.

Use binary search when:

  • Your array is sorted.
  • You will perform many searches on the same data.
  • Your data is large and performance is critical.
  • You need the fastest possible lookup time.

For most small tasks, linear search is perfectly fine. The overhead of sorting might not be worth it. For production systems handling large datasets, binary search is often the standard. If you are dealing with dynamic arrays, you might also want to check our guide on array vs list differences to understand the data structure better.

Performance Comparison with Code

Let's see the performance difference in action. We will create a large array and time both searches. This will give you a practical sense of the speed difference.


import time

# Create a large sorted array
size = 1000000
large_array = list(range(size))
target = size - 1  # Worst-case for linear search

# Linear search time
start = time.time()
linear_search(large_array, target)
linear_time = time.time() - start
print(f"Linear search time: {linear_time:.6f} seconds")

# Binary search time
start = time.time()
binary_search(large_array, target)
binary_time = time.time() - start
print(f"Binary search time: {binary_time:.6f} seconds")

Linear search time: 0.045000 seconds
Binary search time: 0.000002 seconds

The output shows a dramatic difference. Binary search is thousands of times faster. This example uses the worst-case scenario for linear search. Even in average cases, binary search wins by a large margin.

It is important to note that this speed comes with a cost. You must keep your array sorted. If you are frequently adding or removing elements, maintaining sort order can be expensive. You can learn more about efficient insertion with our array insert guide.

Common Pitfalls and Best Practices

One common mistake is using binary search on an unsorted array. This will produce incorrect results. Always ensure your data is sorted before applying binary search. You can use Python's built-in sorted() function to sort your array first.

Another pitfall is off-by-one errors in the binary search logic. Double-check your low and high updates. Use while low <= high to avoid infinite loops. The integer division // is crucial for calculating the middle index.

For linear search, Python offers built-in methods. The in operator and list.index() are optimized C implementations. They are often faster than a custom Python loop. Use them when possible for cleaner code. If you are removing items after finding them, check our array pop guide for best practices.

Conclusion

Both linear and binary search are fundamental tools in Python. Linear search is simple and versatile. It works on any array without preparation. Binary search is fast and efficient but requires sorted data.

Choose linear search for simplicity and small datasets. Choose binary search for performance on large, sorted datasets. Understanding the trade-offs is key to writing efficient Python code.

We hope this guide has clarified the differences. Practice both methods with your own data. Experiment with different array sizes. This hands-on experience will solidify your understanding and help you make the right choice in your projects.