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.
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
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.
Method #2 : Using
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.
- Find number from given list for which value of the function is closest to A
- Python | Find the closest Key in dictionary
- Python program to find second largest number in a list
- Python program to find largest number in a list
- Python program to find smallest number in a list
- Python Program for Find the closest pair from two sorted arrays
- Python | Find maximum length sub-list in a nested list
- Python program to create a list of tuples from given list having number and its cube in each tuple
- Find average of a list in python
- Python | Find Min/Max in heterogeneous list
- Find size of a list in Python
- Python | Find all triplets in a list with given sum
- Python | Find Mean of a List of Numpy Array
- Python | Find missing elements in List
- Python | Find k longest words in given list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to email@example.com. 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.