This is from Knuth's the Art of Programming (via Jon Bentley's Programming Pearls), implemented in Python:
import random
# randomly select m numbers from n candidates
def random_select(m, n):
select = m
result = []
for i in xrange(n):
if random.randint(0, n-i) < select:
result.append(i)
select -= 1
return result
random_select(1000, 8000)
this will generate a list of random numbers in numerical order. It works by iterating over all the integers from 0-n (i.e 0-8000), and randomly selecting them with a probability of(number left to select / number of remaining candidates). It runs in O(n), so do not try it if n is very large compared to m - e.g. selecting ten numbers out of a billion. It uses no memory other than the result list (m) and a few local variables, unlike solutions that rely on shuffling a list of length n.
If you want the result in a random order then shuffle the list afterwards.