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
)
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)).
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
>>> lst = [237, 72, -18, 237, 236, 237, 60, -158, -273, -78, 492, 243]
>>> lst.index(min(lst, key=abs))
2