Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I find the smallest difference between a given number and every element in a list in Python?

Say I have:

[1, 2, 3, 4]

and the integer

6

I want to compare 6 with every element in the list and return the element with the smallest absolute value difference which in this case is 4. Is there an efficient Numpy way to do it?


1 Answers

You can use argmin on the absolute difference to extract the index, which can then be used to extract the element:

a = np.array([1, 2, 3, 4])

a[np.abs(a - 6).argmin()]
# 4
like image 90
Psidom Avatar answered Sep 05 '25 06:09

Psidom



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!