Random sampling from a set of integers
Question: I am working with python 3.2 and I spent a lot of time trouble shooting this,
and I still can't seem to wrap my brain around it.

`number = random.randint ( x0 ,xn )`

I'm generating a random number. It's purpose is to make my code come at me
differently everytime.

For example I have 10 variables of text that I have written. I have solved the
problem of not having these variables appear in the same order at each program
run.

The issue I have is that they now appear randomly everytime. It picks one out
of 10 everytime, instead the first time 10 and next 9. I can't seem to find
out how to exclude the previous ones.

    
    
    thelist = [0]
    
    while i < x
         if number in thelist:
             >>>repeat<<<
         else:
             thelist.append (number)
             if ( number == x0 ):
                 >>>something<<<
             elif ( number == x1 ):
                 >>>something<<<
    

This is what I would imagine the code would look like, everytime you loop one
more number gets appended to the list, so that everytime it picks a number
already in the list it repeats the loop again until it then has used all the
numbers that random.randint can pull.


Answer: Here's a shuffle function:

    
    
    import random
    
    max = 15
    x = list(range(max+1))
    
    for i in range(max, 0, -1):
        n = random.randint(0, i)
        x[n], x[i] = x[i], x[n]
    

This starts with a sorted list of numbers `[0, 1, ... max]`.

Then, it chooses a number from index 0 to index max, and swaps it with index
max.

Then, it chooses a number from index 0 to index max-1, and swaps it with index
max-1.

And so on, for max-2, max-3, ... 1

As yosukesabai rightly notes, this has the same effect as calling
`random.sample(range(max+1), max+1)`. This picks `max + 1` unique random
values from `range(max+1)`. In other words, it just shuffles the order around.
Docs: <http://docs.python.org/2/library/random.html#random.sample>

If you wanted something more along the lines of your proposed algorithm, you
could do:

    
    
    import random
    
    max = 15
    x = range(max+1)
    l = []
    
    for _ in range(max+1):
        n = random.randint(0,max)
        while n in l:
            n = random.randint(0,max)
        l.append(n)
    

