Python | Find closest number to k in given list

Given a list of numbers and a variable K, where K is also a number, write a Python program to find the number in a list which is closest to the given number K.

Examples:

Input : lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8], K = 9.1
Output : 9.35

Input : lst = [9, 11, 5, 3, 25, 18], K = 6
Output : 5

 
Method #1 : Using min() method

In this approach, we use min method from Python and apply a key that finds the absolute difference of each element with K, and returns the element having minimum difference.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find Closest number in a list
  
def closest(lst, K):
      
    return lst[min(range(len(lst)), key = lambda i: abs(lst[i]-K))]
      
# Driver code
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
K = 9.1
print(closest(lst, K))

chevron_right


Output:

9.35

 
Method #2 : Using numpy module

This approach applies the same method but using numpy module. First we convert the given list to an array. Find absolute differnce with K of each element, and return the minimum from it.

filter_none

edit
close

play_arrow

link
brightness_4
code

# Python3 program to find Closest number in a list
import numpy as np
def closest(lst, K):
      
     lst = np.asarray(lst)
     idx = (np.abs(lst - K)).argmin()
     return lst[idx]
      
# Driver code
lst = [3.64, 5.2, 9.42, 9.35, 8.5, 8]
K = 9.1
print(closest(lst, K))

chevron_right


Output:

9.35


My Personal Notes arrow_drop_up


If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.




Article Tags :

Be the First to upvote.


Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.