To find the closest value to a given number in a list of numbers, the easiest way is to use the Python min() function with a lambda function.
lst = [5, 6, 10, 15, 21, 14, -1]
n = 13
closest = min(lst, key=lambda x: abs(x-n))
print(closest)
#Output:
14
You can also use the numpy module to get the closest value to another number in a list.
import numpy as np
lst = [5, 6, 10, 15, 21, 14, -1]
n = 13
np_lst = np.asarray(lst)
idx = (np.abs(np_lst - n)).argmin()
closest = lst[idx]
print(closest)
#Output:
14
When working with collections of data in Python, the ability to get different statistics and information from your data is valuable.
One piece of information which we can get in Python is the closest value of a number in a list.
We can easily find the closest value in a list of a number using the Python min() function and the Python abs() function.
Below is an example showing how you can get the closest value in a list using Python.
lst = [5, 6, 10, 15, 21, 14, -1]
n = 13
closest = min(lst, key=lambda x: abs(x-n))
print(closest)
#Output:
14
Putting this in a function, you can find the closest value of a list with a function in Python as shown below.
list_of_numbers = [5, 6, 10, 15, 21, 14, -1]
num = 13
def closestValue(lst,n):
return min(lst, key=lambda x: abs(x-n))
print(closestValue(list_of_numbers,num))
#Output:
14
Using numpy Module to Find Closest Value in List in Python
You can also use numpy to find the closest value in a list using Python.
First, we need to convert our list to a numpy array and then we can use abs() function and argmin() function.
Below is how you can use numpy to find the closest value in a list.
import numpy as np
lst = [5, 6, 10, 15, 21, 14, -1]
n = 13
np_lst = np.asarray(lst)
idx = (np.abs(np_lst - n)).argmin()
closest = lst[idx]
#Output:
14
Putting this in a function, you can find the closest value of a list with a function as shown below.
import numpy as np
lst = [5, 6, 10, 15, 21, 14, -1]
n = 13
def closestValue(lst,n):
lst = np.asarray(lst)
idx = (np.abs(lst - n)).argmin()
return lst[idx]
print(closestValue(lst,n)
#Output:
14
Hopefully this article has been useful for you to learn how to find the closest value to a given value in a list using Python.