Python Memory Error when using random.sample()
Question: OK, so I have a problem that I really need help with.

My program reads values from a pdb file and stores those values in (array =
[]) I then take every combination of 4 from this arrangement of stored values
and store this in a list called maxcoorlist. Because the list of combinations
is such a large number, to speed things up I would like to simply take a
sample of 1000-10000 from this list of combinations. However, in doing so I
get a memory error on the very line that takes the random sample.

    
    
    MemoryError                               Traceback (most recent call last)
    <ipython-input-14-18438997b8c9> in <module>()
         77     maxcoorlist= itertools.combinations(array,4)
         78     random.seed(10)
    ---> 79     volumesample= random_sample(list(maxcoorlist), 1000)
         80     vol_list= [side(i) for i in volumesample]
         81     maxcoor=max(vol_list)
    
    MemoryError: 
    

It is important that I use random.seed() in this code as well, as I will be
taking other samples with the seed.


Answer: As mentioned in the other answers, the list() call is running you out of
memory.

Instead, first iterate over maxcoorlist in order to find out its length. Then
create random numbers in the range [0, length) and add them to an index set
until the length of the index set is 1000.

Then iterate through maxcoorlist again and add the current value to a sample
set if the current index is in your index set.

**EDIT**

An optimization is to directly calculate the length of maxcoorlist instead of
iterating over it:

    
    
    import math
    n = len(array)
    r = 4
    length = math.factorial(n) / math.factorial(r) / math.factorial(n-r)
    

