Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - find integer closest to 0 in list [duplicate]

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?

like image 703
gadgetmo Avatar asked Aug 12 '12 16:08

gadgetmo


People also ask

How do I find the closest value to a number in a list Python?

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.

How do you check if a number is closer to another number in Python?

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.


1 Answers

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)
like image 61
Óscar López Avatar answered Oct 19 '22 15:10

Óscar López