Change language

Python | Find the closest number to in a given list

| |

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 the min()

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

# Python3 program to find the closest number in the 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))

Exit:

 9.35 

Method # 2: Using numpy

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

# Python3 program to find the closest number in the 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))

Exit :

 9.35 

Shop

Learn programming in R: courses

$

Best Python online courses for 2022

$

Best laptop for Fortnite

$

Best laptop for Excel

$

Best laptop for Solidworks

$

Best laptop for Roblox

$

Best computer for crypto mining

$

Best laptop for Sims 4

$

Latest questions

NUMPYNUMPY

psycopg2: insert multiple rows with one query

12 answers

NUMPYNUMPY

How to convert Nonetype to int or string?

12 answers

NUMPYNUMPY

How to specify multiple return types using type-hints

12 answers

NUMPYNUMPY

Javascript Error: IPython is not defined in JupyterLab

12 answers

News


Wiki

Python OpenCV | cv2.putText () method

numpy.arctan2 () in Python

Python | os.path.realpath () method

Python OpenCV | cv2.circle () method

Python OpenCV cv2.cvtColor () method

Python - Move item to the end of the list

time.perf_counter () function in Python

Check if one list is a subset of another in Python

Python os.path.join () method