dis.obs - 5 months ago 7

Python Question

For e.g. I have a list of number like

`lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]`

And I need 2 numbers at 3 distance from a given number let's say 5,

so the output list should look like this

`output_lst = [2, 8]`

Here by distance I mean the distance on number-line and not in list index. So 3 numbers, 2 distance from 5 would give

`output_lst = [3,3,7]`

What I tired doing was to use nsmallest from heapq like this

`check_number = 5`

output_lst = nsmallest(3, lst, key=lambda x: abs(x - check_number))

But the problem here is that I don't know specify the distance. It will just outputs 3 closest numbers to 5.

`[4,4,5]`

Answer

You can use a list comprehension for that. See this post for more on list comprehensions.

```
>>> lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]
>>> given_numer = 5
>>> distance = 3
>>> [i for i in lst if abs(i-given_numer)==distance]
[2, 8]
```

The logic is quite simple, we just see if the absolute value of the difference between each number and the given number, if so we return the value. Similarly

```
>>> distance = 2
>>> [i for i in lst if abs(i-given_numer)==distance]
[3, 3, 7]
```

Let's complicate a bit and try to use `filter`

and closures. The code is:

_{Just to show that it is an alternative}.

```
def checkdistance(given_number,distance):
def innerfunc(value):
return abs(value-given_number)==distance
return innerfunc
lst = [1, 2, 3, 3, 4, 4, 5, 6, 7, 8, 9]
given_number = 5
distance = 3
checkdistance3from5 = checkdistance(5,3)
list(filter(checkdistance3from5,lst))
```

Source (Stackoverflow)

Comments