14

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
  • 2,964
  • 8
  • 26
  • 39
  • 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

52

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
  • 13,796
  • 25
  • 99
  • 185
Óscar López
  • 225,348
  • 35
  • 301
  • 374
3
reduce(lambda x, y : x if abs(y) > abs(x) else y, your_sequence)
j0k
  • 22,303
  • 28
  • 77
  • 86
verdesmarald
  • 11,334
  • 2
  • 40
  • 59