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.

Easy Python 3.9+ Aug 9, 2026 Algorithms & data structures 15 views 0 copies

Python code

19 lines
Python 3.9+
import 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

stdout
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

  1. Use `min(sorted_list, key=lambda x: abs(x - target))` for a simple but O(n) linear-time solution.
  2. 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

Run this sample

Open the browser IDE to tweak the example and see results without installing anything.

Open editor

More from Algorithms & data structures

Related tutorials and quizzes for this topic.