gadgetmo gadgetmo - 2 months ago 14
Python Question

Python - find integer closest to 0 in list


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?

Answer

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)