Binary Search With Python - The Smart Way to Search Lists

Searching is one of the most common operations in computer science, whether you're looking for a contact in your phone, a book in a library, or a number in a list. While a linear search checks every item one by one (which works, but can be slow), there’s a smarter way which is Binary Search.
Let’s dive into what binary search is, why it’s powerful, and how you can implement it in Python. Example Usage
What is Binary Search?
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)
Start with the full list.
Find the middle element.
If it matches your target, you’re done.
If the target is smaller, repeat the search on the left half.
If the target is larger, search the right half.
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.
When to Use Binary Search
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.





