How to Find the Nearest Value to a Target in a Sorted List in Python
Use bisect to binary-search a sorted list and return the element closest to a target value.
Python code
19 linesimport bisect
def nearest_value(sorted_list, target):
if not sorted_list:
return None
pos = bisect.bisect_left(sorted_list, target)
if pos == 0:
return sorted_list[0]
if pos == len(sorted_list):
return sorted_list[-1]
before = sorted_list[pos - 1]
after = sorted_list[pos]
return before if target - before <= after - target else after
if __name__ == "__main__":
data = [1, 3, 5, 7, 9]
print(nearest_value(data, 6))
print(nearest_value(data, 0))
print(nearest_value(data, 10))
Output
5
1
9
How it works
The bisect.bisect_left function returns the insertion point for the target in the sorted list, keeping the list sorted. If the position is 0, the target is smaller than every element, so the first element is nearest. If the position equals the list length, the target is larger than all elements, so the last element is nearest. Otherwise, we compare the element before and after the insertion point and choose the one with the smaller absolute difference. This runs in O(log n) time, much faster than a linear scan for large lists.
Common mistakes
- Forgetting to handle empty lists, which causes an exception.
- Using bisect.bisect_right instead of bisect_left, which changes the tie-breaking behavior.
- Assuming the input list is sorted when it isn't, leading to incorrect results.
- Comparing absolute differences incorrectly and returning the wrong neighbor.
Variations
- Use `min(sorted_list, key=lambda x: abs(x - target))` for a simple but O(n) linear-time solution.
- Modify to choose the smaller element on ties by using `before if target - before < after - target else after` (strict less-than).
Real-world use cases
- Finding the closest timestamp to a given time in a sorted log or analytics event list.
- Matching a user's requested number to a predefined sizing or pricing tier in a configuration table.
- Locating the nearest sensor reading for a given coordinate in a sorted time-series dataset.
Sponsored
More from Algorithms & data structures
- Binary Search for Ship Capacity in Python medium
- Binary Search on Answer in Python: Koko Eating Bananas medium
- Bucket Numbers into Histogram Bin Counts in Python easy
- Container With Most Water: Two-Pointer Solution in Python medium
- Count Smaller Elements to the Right in Python easy
- Depth First Search Traversal Order in Python easy
Keep learning
Related tutorials and quizzes for this topic.