Kaze Ryuga - 1 year ago 129

Python Question

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".

Recommended for you: Get network issues from **WhatsUp Gold**. **Not end users.**

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]
```

Recommended from our users: **Dynamic Network Monitoring from WhatsUp Gold from IPSwitch**. ** Free Download**