Sometimes, we want to get number closest to a given value from a list of integers with Python.
In this article, we’ll look at how to get number closest to a given value from a list of integers with Python.
How to get number closest to a given value from a list of integers with Python?
To get number closest to a given value from a list of integers with Python, we can use the min function with the key parameter set to a function that returns the absolute difference between the value and the number in the list.
For instance, we write:
my_num = 100
l = [29, 58, 129, 487, 41]
closest = min(l, key=lambda x: abs(x - my_num))
print(closest)
We have my_num which is the number we want to get the closest value to from the list l.
To do that, we call min with l and key set to lambda x: abs(x - my_num)).
lambda x: abs(x - my_num)) returns the absolute difference between x which is an entry in l and my_num.
And then we assign the returned number to closest.
Therefore, closest is 129.
Conclusion
To get number closest to a given value from a list of integers with Python, we can use the min function with the key parameter set to a function that returns the absolute difference between the value and the number in the list.