Closest value and its index in a sorted list - Python

0 votes
I have a sorted list and I would like to find the closest value to the target value and also print the closest value's index. Is that possible on python?
May 28, 2019 in Python by Mahesh
2,055 views

1 answer to this question.

0 votes

You can try this @Mahesh:

lst = [
    13.09409,
    12.18347,
    11.33447,
    10.32184,
    9.544922,
    8.813385,
]

target = 11.5

res = min(enumerate(lst), key=lambda x: abs(target - x[1]))
# (2, 11.33447)
answered May 28, 2019 by Sai

Related Questions In Python

0 votes
1 answer

How do I remove an element from a list by index in Python?

You can use the pop() method to ...READ MORE

answered Jun 21, 2019 in Python by Nisa
• 1,090 points
14,154 views
+4 votes
7 answers

Splitting a List into chunks in Python

Here's a generator that yields the chunks ...READ MORE

answered Apr 13, 2018 in Python by Nietzsche's daemon
• 4,260 points
19,216 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 929 views
0 votes
0 answers
+4 votes
6 answers
0 votes
1 answer

Is there a way to list out in-built variables and functions of Python?

The in-built variables and functions are defined ...READ MORE

answered May 14, 2019 in Python by Junaid
99 views
0 votes
1 answer

How to get permutations of list or a set in Python?

Permutation is an arrangement of objects in ...READ MORE

answered Jul 11, 2019 in Python by Neel
• 3,010 points
1,415 views