How to Find the Closest Value in a List Using Python

min(values, key=lambda x: abs(x - target)) is how you find the closest value in a list using Python. The key turns each item into its distance from the target, and you get back the nearest item:

prices = [189.99, 249.50, 275.00]
min(prices, key=lambda p: abs(p - 250))   # 249.5

Each snippet here ran on Python 3.12.5 in the Windows Command Prompt.

Then you’ll see ties, one-sided matches, dates and sorted lists.

Find the closest value in a list with min() and abs()

Here’s a $250.00 budget against five prices. The second call returns the position, not the value:

prices = [189.99, 249.50, 275.00, 219.95, 310.25]
budget = 250.00

closest = min(prices, key=lambda p: abs(p - budget))
print(f"Closest to ${budget:.2f}: ${closest:.2f}")

i = min(range(len(prices)), key=lambda k: abs(prices[k] - budget))
print(f"Index {i}, off by ${abs(prices[i] - budget):.2f}")

Output:

Closest to $250.00: $249.50
Index 1, off by $0.50
Command Prompt output of Python min() with an abs() key finding the price closest to a 250 dollar budget and its index
The $249.50 item wins, and it sits at index 1, just 50 cents under budget.

Passing range(len(prices)) makes min() compare positions. For the position of a known value, getting the index of an element in a Python list is simpler.

What happens when two values are equally close?

With a target of 71, both 70 and 72 are one degree away. min() keeps the first one it meets. A tuple key makes the rule explicit:

temps = [68, 74, 70, 72]
target = 71

print(min(temps, key=lambda t: abs(t - target)))         # first tie wins
print(min(temps, key=lambda t: (abs(t - target), t)))    # smaller value wins
print(min(temps, key=lambda t: (abs(t - target), -t)))   # larger value wins

Output:

70
70
72
Command Prompt output of Python closest value tie-breaking with a tuple key choosing the smaller or larger value
The plain key returns 70 because it comes first, the tuple keys pick 70 or 72 on purpose.

Tuples compare item by item, so the second element only counts when distances match. I use this whenever the rule matters. Sorting by more than one field works the same way in sorting a list of tuples in Python.

Find the closest value below or above a target

Sometimes “closest” has a direction, like a box that must fit the item. Filter first, then take max() or min():

sizes = [8, 12, 16, 24, 32]
need = 20

below = max((s for s in sizes if s <= need), default=None)
above = min((s for s in sizes if s >= need), default=None)
print(f"Largest at or below {need}: {below}")
print(f"Smallest at or above {need}: {above}")

Output:

Largest at or below 20: 16
Smallest at or above 20: 24

Don’t skip default=None. Without it, an empty filter raises ValueError.

Find the closest date in a list of dictionaries

The key can reach into a dictionary, and abs() works on a timedelta. Here I’m matching a 2:30 PM pickup on November 25, 2026, to the nearest flight:

from datetime import datetime

flights = [
    {"flight": "UA 512", "departs": datetime(2026, 11, 25, 9, 40)},
    {"flight": "DL 208", "departs": datetime(2026, 11, 25, 13, 15)},
    {"flight": "AA 917", "departs": datetime(2026, 11, 25, 16, 5)},
]
wanted = datetime(2026, 11, 25, 14, 30)

best = min(flights, key=lambda f: abs(f["departs"] - wanted))
gap = abs(best["departs"] - wanted)
print(best["flight"], best["departs"].strftime("%I:%M %p"), "| off by", gap)

Output:

DL 208 01:15 PM | off by 1:15:00
Command Prompt output of Python min() finding the flight in a list of dictionaries closest to a 2:30 PM pickup time
DL 208 at 1:15 PM is the nearest departure, 1 hour 15 minutes early.

Any record shape works the same way, including a list of lists in Python, where you’d write row[1] in the key.

Use bisect for the closest value in a sorted list

min() checks every item. On a sorted list, bisect_left() finds the insertion point in about log n steps, so you’ll compare just two neighbors:

from bisect import bisect_left

def closest_sorted(values, target):
    i = bisect_left(values, target)
    nearby = values[max(i - 1, 0):i + 1]      # at most two neighbors
    return min(nearby, key=lambda v: abs(v - target))

zips = sorted([10001, 30301, 60601, 77001, 94105])
for z in (2000, 45000, 77001, 99999):
    print(z, "->", closest_sorted(zips, z))

Output:

2000 -> 10001
45000 -> 30301
77001 -> 77001
99999 -> 94105
Command Prompt output of a Python bisect function finding the closest ZIP code in a sorted list, including both ends
Targets past either end get the first or last ZIP, and an exact match returns itself.

The slice never goes out of range, so targets past either end just get the first or last item. The idea is the classic binary search in Python.

Using NumPy instead? np.abs(arr - target).argmin() is the fast path, and finding the closest value in a NumPy array walks through it.

If lists are your thing this week, try one of these:

Frequently asked questions

How do I find the closest number in a list in Python?

Use min(values, key=lambda x: abs(x - target)).

How do I get the index of the closest value?

Use min(range(len(v)), key=lambda i: abs(v[i] - target)).

Which value wins when two are equally close?

The first one in list order. The key (abs(x - target), x) prefers the smaller value.

How do I find the closest value that isn’t above the target?

Filter, then take the maximum: max((x for x in v if x <= target), default=None).

Is there a faster way for a sorted list?

Yes. Use bisect.bisect_left() and compare the two neighbors.

Where is the key argument of min() documented?

See min() in the Python docs.