15

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?

Community
  • 1
  • 1
gadgetmo
  • 3,058
  • 8
  • 27
  • 41
  • http://stackoverflow.com/questions/9706041/finding-index-of-an-item-closest-to-the-value-in-a-list-thats-not-entirely-sort Looks like the same question was asked and answered. – Tim Aug 12 '12 at 16:12

2 Answers2

54

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)
nbro
  • 15,395
  • 32
  • 113
  • 196
Óscar López
  • 232,561
  • 37
  • 312
  • 386
4
reduce(lambda x, y : x if abs(y) > abs(x) else y, your_sequence)
j0k
  • 22,600
  • 28
  • 79
  • 90
verdesmarald
  • 11,646
  • 2
  • 44
  • 60