Search code examples
pythonlistnumpysubtraction

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?


Solution

  • 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