Kaze Ryuga Kaze Ryuga - 9 months ago 66
Python Question

How to find the smallest closest number in a list in python

I want to know how can I find the smallest closest number in a list to a given number.
For example:

number = 20

list_of_numbers = [4, 9, 15, 25]


I tried this:

min(list_of_numbers, key=lambda x:abs(x-number))


The output is 25 and not 15. The problem is that it always gives me the "biggest closest" and not the "smallest closest".

Answer Source

You could make the key also contain the number itself and use that for breaking ties:

min(list_of_numbers, key=lambda x: (abs(x - number), x))

Your behavior is strange, though. It might be a bug. You might be able to work around it by using sorted, which is stable:

sorted(list_of_numbers, key=lambda x: abs(x - number))[0]