October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsClean PCRecommendedOne scan can reveal what keeps slowing WindowsLook for cleanup and repair opportunities.Run ScanOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk3 min

How to Find the Closest Value in an Array Using Python

Use Python’s min() with an absolute-distance key to select the nearest value, or NumPy’s argmin() to get the index and retrieve the closest array element.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use min() with an absolute-distance key to get the closest value from a Python iterable. If you also need the position in a NumPy array, subtract the target, take absolute values, and use argmin() to find the index.

Find the closest value in a Python list

For a list or other iterable of numeric values, pass min() a key function that measures each value’s distance from the target:

values = [1, 5, 9, 14]
target = 8
closest = min(values, key=lambda x: abs(x - target))

print(closest)  # 9

The key function computes abs(x - target) for each item, so min() returns the original item with the smallest distance—not the distance itself. The method works with comparable numeric values and scans the iterable once. Python’s built-in functions documentation specifies that when multiple items are minimal, min() returns the first one encountered.

Handle an empty iterable

If the iterable might be empty, min() raises ValueError unless you provide default. Choose a default that makes sense for the rest of your program:

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
closest = min(values, key=lambda x: abs(x - target), default=None)

Alternatively, check that the collection contains values before calling min().

Get the closest value and index in a NumPy array

With NumPy, use argmin() on the absolute differences to get the position, then index the original array to retrieve the value:

import numpy as np

arr = np.array([1, 5, 9, 14])
target = 8
idx = np.abs(arr - target).argmin()
closest = arr[idx]

print(idx)      # 2
print(closest)  # 9

idx is the index of the closest element, while closest is the element stored there. The NumPy 2.2 argmin reference documents that ties return the index of the first occurrence.

Multidimensional arrays

Without an axis argument, argmin() returns an index into the flattened array. To find a closest value separately along rows or columns, specify the relevant axis. If you use the default flattened result but need coordinates in the original dimensions, convert the index with numpy.unravel_index().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Check for an empty array

Check that a NumPy array has elements before calling argmin(). An empty array has no minimum, so decide whether your application should return a fallback value or raise an error before performing the reduction.

Choose the approach that matches your data

  • Python list or general iterable; value only: use min(values, key=lambda x: abs(x - target)). It needs no NumPy dependency.
  • NumPy array; index and value: use np.abs(arr - target).argmin() for the index, then access arr[idx].
  • Sorted sequence with repeated queries: use bisect_left() to find where the target would be inserted, then compare the neighboring values. This approach relies on the sequence already being sorted.

Python’s bisect documentation describes bisect_left() as locating an insertion point that separates values less than the target from values greater than or equal to it. When using it, account for insertion positions at both ends of the sequence, where only one neighbor exists.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Decide how ties and special values should work

Equal distances

Both min() and NumPy’s argmin() choose the first encountered minimum. For example, with values [5, 9] and target 7, both are equally close, so the first item wins. If your application should instead prefer the smaller value or apply another rule, encode that rule explicitly in your selection logic.

NaN values

If the data may contain NaNs, do not assume ordinary argmin() will ignore them. Decide whether NaNs should be excluded or treated as a special case, and use an appropriate NaN-aware NumPy operation if that matches your intended behavior.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Define distance for non-scalar data

These examples use one-dimensional numeric distance: abs(value - target). For points, vectors, or domain-specific values, choose the distance metric that represents closeness in your application before selecting a minimum.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

Your email address will not be published. Required fields are marked *

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Windows Errors? Fix Them Before They SpreadFree repair scan
Outdated Drivers Are Slowing You DownFree scan - exact matches

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.