You can use random.sample
:
>>> random.sample(xrange(1,50), 6)
[26, 39, 36, 46, 37, 1]
"The worksheet recommends displaying each number and setting it to zero, but I don't see how that would help."
Assuming this is an assignment and you need to implement the sampling yourself, you could take a look at how random.sample
is implemented. It's really informative, but may be too complicated for your needs since the code also ensures that all sub-slices will also be valid random sample. For efficiency, it also uses different approaches depending on the population size.
As for the worksheet, I believe it assumes you're starting off with a list of numbers from 1 to 49 and suggests that you replace numbers that you're selected with 0 so there can be skipped if reselected. Here's some pseudo code to get you started:
population = range(1, 50) # list of numbers from 1 to 49
sample = []
until we get 6 samples:
index = a random number from 0 to 48 # look up random.randint()
if population[index] is not 0: # if we found an unmarked value
append population[index] to sample
set population[index] = 0 # mark selected
If you wish to attempt something different, there are many other approaches to consider e.g. randomising the list then truncating, or some form of reservoir sampling.
Good luck with your assignment.