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
3,209 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
2 answers

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

Delete the List and its element: We have ...READ MORE

answered Jun 7 in Python by sahil
• 540 points
31,045 views
0 votes
1 answer

how to solve this IndexError: list index out of range in python and streamlit?

Hi,  @Erick, To solve the “index error: list ...READ MORE

answered Sep 24 in Python by Roshni
• 4,030 points
77 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 1,373 views
0 votes
0 answers
+4 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,800 points
1,014 views
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
155 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
3,722 views