Question: I'm trying to generate (pseudo)random numbers using the random module. I need the numbers generated to not be too close to each other in terms of range. For example, if a number of n is generated, then another number x cannot be n +- 5.

```
from random import randint

i = 10

j_list = []
k_list = []

while i != 0:

    j = randint(-10, 10)
    k = randint(-15, 15)

    j_list.append(j)
    k_list.append(k)

    i -= 1

print("J list is: {} and K list is {}".format(j_list, k_list))

```

For example, when I ran it last time, I got following output:

```
J list is: [-4, 5, 2, -3, 7, -4, 3, -1, -1, -6] and K list is [10, 3, -7, -1, -5, -11, 3, 8, 1, -7]

```

As you can see, the 1st and 3rd elements of j\_list (that is, j\_list[1:3]) are within +- 5 of one another. This is not something I want; I want every element in the list to produce values that are out of certain range.

Is there any way of doing this?

Answer: 
First of all, using a for loop is better than using a while loop here:

```
# One line and you know the loop range immediately
for i in range(10):
    print(i)

# Three lines and takes the reader two seconds to comprehend
i = 10
while i != 0:
    i -= 1
    print(i)

```

Now to answer your question, you can use random.choice to exclude range(j - 5, j + 5):

```
from random import randint, choice

j_list = []
k_list = []

for i in range(10):

    j = randint(-10, 10)
    k = choice([n for n in range(-15, 15) if n not in range(j - 5, j + 6)])

    j_list.append(j)
    k_list.append(k)

print("J list is: {} and K list is {}".format(j_list, k_list))

```

If you only want to use randint, an alternative is to use a while loop to keep rerolling value k until it does not fall in the j +- 5 range:

```
from random import randint

j_list = []
k_list = []

for i in range(10):

    j = randint(-10, 10)
    k = randint(-15, 15)

    while abs(j - k) <= 5:

        k = randint(-15, 15)

    j_list.append(j)
    k_list.append(k)

print("J list is: {} and K list is {}".format(j_list, k_list))

```

As @ShadowRanger points out, the while loop strategy is less computational demanding and is easier to read so you might want to go for that.
How about something along these lines, this you can easily alter the amount of `iterations`, the range of your `randint` and the permissible space between your `randint`

```
from random import randint

def not_within_five(lista):
    i = 0
    while i < 10:
        x = randint(0, 50) 
        if lista[i] in range(x-5, x+5):
            continue
        else:
            lista.append(x)
            i += 1

j = []
k = []

j.append(randint(0, 50))
k.append(randint(0, 50))

not_within_five(j)
not_within_five(k)

print(f"J list is {j}\n")
print(f"K list is {k}")

```

**Output**

> 
> 
> ```
> (xenial)vash@localhost:~/python$ python3.7 randi.py
> J list is [19, 31, 49, 3, 9, 42, 29, 41, 22, 0, 35]
> 
> K list is [42, 19, 13, 27, 42, 1, 26, 10, 17, 40, 47]
> 
> ```
> 
>