How to Find the Closest Value in a List Using Python?

In this tutorial, I will explain how to find the closest value in a list using Python. As a developer working on various projects, I came across a scenario where I needed to find the closest value in a list, then I researched more about this topic and found a few effective methods to accomplish this task. Let us learn more about this topic with suitable examples.

Find the Closest Value in a List Using Python

To find the closest value in a list using Python, you can use the min() function with a custom key that calculates the absolute difference between each element and the target value. For example, if you have a list numbers = [10, 5, 8, 12, 3] and a target value of 7, you can find the closest value using min(numbers, key=lambda x: abs(x - 7)), which will return 8 as it has the smallest absolute difference from the target value.

Given a list of numbers and a target value, we want to find the number in the list that is closest to the target. For instance, if we have the list [1.3, 5.24, 0.89, 21.0, 5.27, 1.3] and the target value is 5.0, the closest number in the list would be 5.24.

Read How to Sort a List in Python Without Using the sort() Function?

Approach 1: Loop and Tracking Minimum Difference

One straightforward approach to finding the closest value is to loop through the list and keep track of the number with the minimum absolute difference from the target value. Here’s how we can implement this in Python:

def find_closest(numbers, target):
    closest = numbers[0]
    min_diff = abs(target - closest)

    for num in numbers:
        diff = abs(target - num)
        if diff < min_diff:
            min_diff = diff
            closest = num

    return closest

In this code:

  1. We initialize closest as the first number in the list and min_diff as the absolute difference between the target and closest.
  2. We loop through each number num in the list.
  3. We calculate the absolute difference diff between the target and the current number.
  4. If diff is smaller than min_diff, we update min_diff and closest accordingly.
  5. After the loop ends, we return the closest number.

Here’s an example of using this function:

cities = ["New York", "Los Angeles", "Chicago", "Houston", "Phoenix"]
distances = [2789.6, 2789.2, 1745.2, 1627.6, 2288.4]  # Distances from Seattle in miles
target_distance = 1700.0

closest_city = cities[distances.index(find_closest(distances, target_distance))]
print(f"The closest city to {target_distance} miles from Seattle is {closest_city}.")

Output:

The closest city to 1700.0 miles from Seattle is Chicago.

You can see the output in the screenshot below.

Find the Closest Value in a List Using Python

In this example, we have a list of cities and their corresponding distances from Seattle. By using the find_closest() function, we can find the distance closest to 1700 miles and retrieve the corresponding city name.

Check out How to Check if Any Element in a List is Present in Another List using Python?

Approach 2: Use min() with Key Function

Python’s built-in min() function can be used with a key function to find the closest value in a list more concisely. The key function calculates the absolute difference between each number and the target and min() returns the number with the minimum difference. Here’s how we can implement this approach:

def find_closest(numbers, target):
    return min(numbers, key=lambda x: abs(target - x))

This one-line function uses min() with a lambda function as the key. The lambda function calculates the absolute difference between the target and each number x in the list. min() then returns the number with the minimum difference.

Here’s an example of usage:

prices = [250000, 315000, 280000, 190000, 320000]  # Median home prices in different cities
user_budget = 200000

closest_price = find_closest(prices, user_budget)
print(f"The closest home price to the user's budget of ${user_budget:,} is ${closest_price:,}.")

Output:

The closest home price to the user's budget of $200,000 is $190,000.

You can see the output in the screenshot below.

How to Find the Closest Value in a List Using Python

In this example, we have a list of median home prices in different cities and a user’s budget. By using the find_closest() function with min() and a lambda key, we can find the home price closest to the user’s budget.

Read How to Capitalize the First Letter of Every Word in a List using Python?

Handle Ties

In some cases, there might be multiple numbers in the list that are equally close to the target value. If you want to handle ties in a specific way, such as returning the smallest or largest number among the ties, you can modify the approaches accordingly.

For example, to return the smallest number in case of ties, you can update the find_closest() function like this:

def find_closest(numbers, target):
    return min(numbers, key=lambda x: (abs(target - x), x))

Here, the lambda function returns a tuple (abs(target - x), x), where the first element is the absolute difference and the second element is the number itself. min() will compare the tuples lexicographically, so if there are ties in the absolute difference, it will compare the numbers and return the smallest one.

Check out How to Find the Index of the Maximum Value in a List using Python?

Conclusion

In this tutorial, I explored two approaches to find the closest value in a list using Python such as loop and tracking minimum difference and using min() with a key function. I also covered handling ties.

You can also read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.