Skip to main content

Command Palette

Search for a command to run...

Binary Search With Python - The Smart Way to Search Lists

Updated
Binary Search With Python - The Smart Way to Search Lists

Let’s dive into what binary search is, why it’s powerful, and how you can implement it in Python. Example Usage

Binary Search is an efficient algorithm for finding an item in a sorted list. Instead of checking every single element, it cuts the search space in half with each step. This means it can find items much faster than a linear search.

Imagine looking for a word in a dictionary. You don’t start from the first page, you open somewhere in the middle and narrow down based on whether your word comes before or after the one you landed on. That’s binary search in action.

How It Works (Step-by-Step)

  1. Start with the full list.

  2. Find the middle element.

  3. If it matches your target, you’re done.

  4. If the target is smaller, repeat the search on the left half.

  5. If the target is larger, search the right half.

  6. Repeat until you find the target or the sublist is empty.

Python Implementation

Here’s a Python function for binary search

binary_search(sorted_list, target):
    start_index = 0
    end_index = len(sorted_list) - 1

    while start_index <= end_index:
        middle_index = (start_index + end_index) // 2
        middle_value = sorted_list[middle_index]

        if middle_value == target:
            return middle_index  # found target
        elif middle_value > target:
            end_index = middle_index - 1  # search the left half
        else:
            start_index = middle_index + 1  # search the right half

    return None  # no target found
pythonCopyEditnumbers = [2, 4, 6, 8, 10, 12]
print(binary_search(numbers, 8))   # output is 3
print(binary_search(numbers, 5))   # output is None
  • 8 is found at index 3 in the list.

  • 5 is not in the list, so the function returns None.

Why is Binary Search so fast

Binary search has a time complexity of O(log n), which means it handles large datasets very efficiently. For example:

  • A list with 1,000 items takes at most 10 steps to search.

  • A list with 1,000,000 items? Just 20 steps!

    Compare that to linear search’s O(n), which could take 1,000,000 steps in the worst case.

Use binary search when:

  • Your data is sorted

  • Speed is important

  • You want clean, readable logic for finding items

Binary search is a classic algorithm that’s still relevant today. It’s elegant, fast, and easy to implement -once you understand it. Whether you're prepping for interviews or building efficient apps, binary search is a must-have in your toolbox.

More from this blog

P

Practical Web Development Tips & Guides - By Ayobami Omotayo

12 posts

TechBytesWithAyo by Ayobami Omotayo is your go-to hub for bite-sized insights on web development, blockchain, AI, and the latest tech trends, simplifying complex topics, one byte at a time.