1

I just asked the following question:

Python - find integer closest to 0 in list

The best answer was to use: min(lst, key=abs).

That code returns the item from the list.

How do I get the item number from the list? (i.e. 2 instead of -18)

Community
  • 1
  • 1
gadgetmo
  • 3,058
  • 8
  • 27
  • 41

4 Answers4

4

You'd need to augment your list with indices:

min(enumerate(lst), key=lambda x: abs(x[1]))

It'll return the index and closest-to-zero value, use [0] if you only need the index.

On your example:

>>> example = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
>>> min(enumerate(example), key=lambda x: abs(x[1]))
(2, -18)
>>> min(enumerate(example), key=lambda x: abs(x[1]))[0]
2

This is very efficient (worst-case O(n)); you can use example.index(min(example, key=abs)) as well, but that has to go through the list twice in the worst case (O(2n)).

Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

Try:

lst.index(min(lst, key=abs))

kamek
  • 2,390
  • 2
  • 19
  • 15
1

One way is after finding the integer you want to find, you can use "index"...

result = min(lst, key=abs)
index = lst.index(result)
print(index) # prints 2
Mark Hildreth
  • 42,023
  • 11
  • 120
  • 109
1
>>> lst = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
>>> lst.index(min(lst, key=abs))
2
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504