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
9,872 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

+1 vote
4 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, 2020 in Python by sahil
• 500 points
280,801 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 25, 2020 in Python by Roshni
• 10,480 points
28,464 views
0 votes
2 answers
+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 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 4,449 views
0 votes
1 answer
+5 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,790 points
4,102 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
2,233 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,020 points
8,917 views
webinar REGISTER FOR FREE WEBINAR X
REGISTER NOW
webinar_success Thank you for registering Join Edureka Meetup community for 100+ Free Webinars each month JOIN MEETUP GROUP