Question: This might be a simple math problem for many, but it has proven to be a bit confusing for my humble mind.

Given a list l:

```
l = [0,20,40,80,100]

```

And a random int between the first and the last elements:

```
r = randrange(l[0], l[-1])

```

How can I get the "lowest closest" index?. Let us suppose that the random resulting int is 39. In this case, I want to get the index of number 1 (The second), considering that the int 39 is between the range of 20 and 40.

Here's the code I'm using to philosophize about it:

```
from random import randrange
l = [0,20,40,80,100]
for e in l:
    r = randrange(l[0], l[-1])
    print str(e-r) + " | " + str((e, r))

```

Answer: 
If your list is sorted use Python's [`bisect` module](https://docs.python.org/2/library/bisect.html):

```
>>> import bisect
>>> a = [0, 20, 40, 80, 100]
>>> n = 39
>>> bisect.bisect_left(a, n)
2

```

Note that `bisect_left` gives you the index of an insertion point needed to maintain sorted order. In your case that's element after the one you are looking for. You could simply subtract 1 from the result, but you then run the risk of getting an incorrect result of `-1`. A simple helper function fixes this and throws an `ValueError` when there is no valid result.

```
>>> def find_lt_index(a, x):
...     i = bisect.bisect_left(a, x)
...     if i:
...         return i-1
...     raise ValueError
...
>>> find_lt_index(a, n)
1

```
```
def closest(l, r):
    for i in l:
        if i >= r:
            return l.index(i)-1
    return None

```