# Randomnly Select Numbers From A List With A Condition

## 04 September 2019 - 1 answer

I have a `list(range(30000))`. I need to randomnly select numbers inside it such that, it takes a certain count of numbers say `'n'` in total at the same time it should take `'k'` number of values between two index positions.

For example:

``````a = [1,2,3,4,5,,6,7,8......20,21,22......88,89.....30k]
``````

I need to select `5000` numbers in total. `'x'` numbers between `0th index to 100th index`, `'y'` numbers between `100 to 200` etc.

There is no hard rule that it should select `5000` numbers itself. But it should sure lie between `0-100, 100-200` etc.

I saw `random.choice` but how to give it a condition

To put the question accurately: I need `50` numbers from `0-100,200-300 etc.`

Here's one way to approach this:

``````import random
# define the sample size of each interval
# or for your specific case generate a sequence
# that adds up to 5000
size = [5, 2, 10]
n = 300
step = 100

# iterate over both a range (or sequence) and size
# and take random samples accordingly
out = [random.sample(list(range(i-step,i)), k)
for i, k in zip(range(step, n+step, step), size)]
``````

``````print(out)
[[6, 86, 96, 62, 53], [115, 176], [245, 259, 297, 249, 225, 281, 264, 274, 275, 206]]
``````