Seeded Python RNG showing non-deterministic behavior with sets
Question: I'm seeing non-deterministic behavior when trying to select a pseudo-random
element from sets, even though the RNG is seeded (example code shown below).
Why is this happening, and should I expect other Python data types to show
similar behavior?

Notes: I've only tested this on Python 2.7, but it's been reproducible on two
different Windows computers.

Similar Issue: The issue at [Python random seed not working with Genetic
Programming example code](http://stackoverflow.com/questions/6614447/python-
random-seed-not-working-with-genetic-programming-example-code) may be similar.
Based on my testing, my hypothesis is that run-to-run memory allocation
differences within the sets is leading to different elements getting picked up
for the same RNG state.

So far I haven't found any mention of this kind of caveat/issue in the Python
docs for set or random.

Example Code (randTest produces different output run-to-run):

    
    
    import random
    
    ''' Class contains a large set of pseudo-random numbers. '''
    class bigSet:
        def __init__(self):
            self.a = set()
            for n in range(2000):
                self.a.add(random.random())
            return
    
    
    ''' Main test function. '''
    def randTest():
        ''' Seed the PRNG. '''
        random.seed(0)
    
        ''' Create sets of bigSet elements, presumably many memory allocations. ''' 
        b = set()
        for n in range (2000):
            b.add(bigSet())
    
        ''' Pick a random value from a random bigSet. Would have expected this to be deterministic. '''    
        c = random.sample(b,1)[0]
        print('randVal: ' + str(random.random()))           #This value is always the same
        print('setSample: ' + str(random.sample(c.a,1)[0])) #This value can change run-to-run
        return
    


Answer: I'm fairly certain you're correct, and the issue is caused by the run-to-run
memory allocation differences for `set`. When I changed your program to use
lists instead of sets, I got deterministic behavior:

    
    
    import random
    
    ''' Class contains a large list of pseudo-random numbers. '''
    class bigList:
        def __init__(self):
            self.a = [random.random() for n in range(2000)]
    
    ''' Main test function. '''
    def randTest():
        ''' Seed the PRNG. '''
        random.seed(0)
    
        ''' Create lists of bigList elements, presumably many memory allocations. '''
        b = [bigList() for n in range(2000)]
    
        ''' Pick a random value from a random bigSet. Would have expected this to be deterministic. '''
        c = random.sample(b, 1)[0]
        print('randVal: ' + str(random.random()))  # This value is always the same
        # and so is this now...
        print('setSample: ' + str(random.sample(c.a, 1)[0]))
    
    randTest()
    

