Joesh
Joesh

Reputation: 67

return closest item to a given value in a list and its index

I found the following one code for searching for the nearest value to 11.1 in list a, eg: a=(1,2,3,4,5,6,7,8,9,10,11,12)

min(enumerate(a), key=lambda x: abs(x[1]-11.1))

How does the code pick the correct index? Are there any better implementations?

Upvotes: 0

Views: 98

Answers (1)

Anand S Kumar
Anand S Kumar

Reputation: 91009

enumerate() function in each iteration returns a tuple where the first element is the index and the second element is the actual element of the list.

Then you are finding the minimum of it where the key is - abs(x[1] - 11.1) - which gives the absolute difference between the element and 11.1 .

Example to show enumerate behavior -

>>> l =  [10,11,12]
>>> a = enumerate(l)
>>> next(a)
(0, 10)
>>> next(a)
(1, 11)
>>> next(a)
(2, 12)

Upvotes: 1

Related Questions