Possible Duplicate:
finding index of an item closest to the value in a list that's not entirely sorted
I've got a list of positive and negative numbers in Python ([237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
). I want to find the number which is closest to 0. How do I do this?
We can find the nearest value in the list by using the min() function. Define a function that calculates the difference between a value in the list and the given value and returns the absolute value of the result. Then call the min() function which returns the closest value to the given value.
The math. isclose() method checks whether two values are close to each other, or not. Returns True if the values are close, otherwise False. This method uses a relative or absolute tolerance, to see if the values are close.
How about this:
lst = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
min((abs(x), x) for x in lst)[1]
A nice and much shorter answer:
min(lst, key=abs)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With