Find nearest value in the list in Python

Welcome to our tutorial on finding the nearest value in a list using Python. This guide will help you locate the value in a list that is closest to a given input value. Whether you’re dealing with sorted or unsorted lists, we’ll explore various methods to tackle this problem. For example, suppose that the original list is [9,8,6,2,10] and the given value is 3. Then 6 should be returned as an output as it is the closest to 3. To find the closest match, we will practice different techniques and methods.

A Brief Overview

This tutorial discusses the following cases.
Given an input list and a value:
List=[29, 32, 14, 19, 56, 97, 24, 46, 74]
Input Value specified by the user: 22
Problem 1: Find the closest value in the list.
Output:24
Problem 2: When the two numbers are at equal distance
List=[29, 32, 14, 19, 56, 97, 24, 46, 74]
Input Value specified by user: 19
(a) find the closest lower value in the list.
Output:14
(b) Find the closest higher value in the list.
Output:24
Problem 3: Find the two closest values in the given input list.
List = [29, 14, 19, 56, 97, 32, 24, 46, 74]
Input Value specified by user: 29,32

Let’s discuss all these cases for sorted and unsorted lists along with examples. learn more about Python Lists.

Problem 1: Find the Nearest value in a list to A user-specified input value

Suppose you have the following list:

list1 = [22, 12, 51, 23, 48, 16, 34, 61]

The user specifies the input value as 43. Our goal is to find the closest value in the list.

Solution:

We can use the min() function in Python to accomplish this task. First, we’ll define a function that calculates the absolute difference between each element in the list and the given input value. Then, we’ll use min() to find the element with the smallest absolute difference.

import numpy as np

def closest_value(input_list, input_value):

  arr = np.asarray(input_list)

  i = (np.abs(arr - input_value)).argmin()

  return arr[i]

if __name__ == "__main__" :

  list1 = [22, 12, 51, 23, 48, 16, 34, 61]

  num=int(input("Enter the value: "))

  val=closest_value(list1,num)

  print("The closest value to the "+ str(num)+" is",val)
find closest value in list in python output

In this code, we first convert the list into a NumPy array, calculate the absolute differences, and then find the index corresponding to the minimum difference, which gives us the closest value.

You can also achieve the same result using a lambda function to make the code more concise:

def closest_value(input_list, input_value):

  difference = lambda input_list : abs(input_list - input_value)

  res = min(input_list, key=difference)

  return res

if __name__ == "__main__" :

  list1 = [22, 12, 51, 23, 48, 16, 34, 61]

  num=int(input("Enter the value: "))

  val=closest_value(list1,num)

  print("The closest value to the "+ str(num)+" is",val)
find the nearest value in list python code output

Problem 2: find the closest value When the two numbers are at an equal distance

When two numbers are equidistant from the target value, the previous solutions will return the closest lower value. If you require the closest higher value, you can modify the code as follows:

Solution:

def closest_value(input_list, input_value):

  input_list.sort(reverse=True)

  difference = lambda input_list : abs(input_list - input_value)

  res = min(input_list, key=difference)

  return res

if __name__ == "__main__" :

  list1 = [29, 32, 14, 56, 97, 24, 46, 74]

  num=int(input("Enter the value: "))

  val=closest_value(list1,num)

  print("The closest value to the "+ str(num)+" is",val)
Code output for finding closest value When the two numbers are at equal distance

problem 3: Find the two closest values in the list

To find the two closest values in a list, we’ll calculate the difference between each pair of values and select the pair with the minimum difference.

Solution:

In the code given below, we have created a temp variable that will store the minimum difference. We have initialized it with the maximum value in the list. Then we have used two loops to traverse through the list. At the first iteration of for loop, the num1 variable stores the 2nd number i.e. 32 whereas the while loop will calculate the difference between all the values before 32 and store the minimum difference in the temp variable. The variables first_num and sec_num are the two numbers that generated the minimum result. Similarly, on the second iteration, the num1 becomes 14. The while loop first calculates the difference between 14 and 32, then decrements j and extracts the first element and num2 in the list.

 
list1 = [29, 32, 14, 56, 97, 24, 46, 74]

 temp=max(list1)

 for i in range(1, len(list1)):

    num1=list1[i]

    j=i-1

    while(j>=0):

      num2=list1[j]

      res=abs(num1-num2)

      if res<temp:

        temp=res

        first_num=num1

        sec_num=num2

      j=j-1

 print(first_num,sec_num) 
output for value in list

In this comprehensive tutorial, we’ve covered how to find the nearest value in a list, even when two values are equally close. You’ve learned multiple methods to tackle this common problem in Python. Feel free to explore further and share your feedback in the comments. For more Python tutorials and programming resources, visit our website.

Leave a Comment

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