Python Question

Find The Closest Number To Numbers Given In A List ~ Python

How would you find the closest number in comparison to numbers given in a list?
This is what I have tried but I have come of unsuccessfull:

setted_list = [2,9,6,20,15]
value_chosen = 17

while True:
final_value = setted_list[0]
if setted_list[1] - value_chosen < setted_list[0] - value_chosen:
final_value = setted_list[1]
if setted_list[2] - value_chosen < setted_list[1] - value_chosen:
final_value = setted_list[2]
if setted_list[3] - value_chosen < setted_list[2] - value_chosen:
final_value = setted_list[3]
if setted_list[4] - value_chosen < setted_list[3] - value_chosen:
final_value = setted_list[4]
print(final_value)


My Output is always what is inside Index 2 of my list (aka setted_list[2])
Where have I gone wrong in my algorithm?

Answer Source

If you are too new to understand lambda functions yet,

   minimum = float("inf")
   setted_list = [2,9,6,20,15]
   value_chosen = 17
   for val in setted_list:
       if abs(val - value_chosen) < minimum:
           final_value = val
           minimum = abs(val - value_chosen)


   print final_value
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download