python is there an inbuilt in way to return a list generator instead of list from random.sample
<p>I use <code>random.sample</code> to sample from a very large range depending on the input load. Sometimes the sample itself is very large and since it is a list it occupies a lot of memory.</p>

<p>The application does not necessarily use all the value in the list. 
It would be great if <code>random.sample</code> can return a list generator instead of a list itself. </p>

<p>Right now I have a wrapper that divides the large input range into equal sized buckets and use <code>randint</code> to select a random number from each <code>n / sample_size</code> buckets.</p>

<p>edit: In my case input is continuous, I had this wrapper function to simulate random.sample as a generator but this is not truly replicating the functionality as it skips some elements in the end.</p>

<pre><code>import random
def samplegen( start, end, sample_size ):
   bktlen = ( end - start ) / sample_size
   for i in xrange( sample_size ): #this skips the last modulo elements
      st = start + (i * bktlen)
      yield random.randrange( st, st + bktlen )
</code></pre>

<p>Why not something like the following -- the set <code>seen</code> only grows to a function of <code>k</code>, not necessarily to the size of <code>population</code>:</p>

<pre><code>import random

def sample(population, k):
    seen = set()

    for _ in range(k):
        element = random.randrange(population)
        while element in seen:
            element = random.randrange(population)

        yield element
        seen.add(element)

for n in sample(1000000, 10):
    print(n)
</code></pre>

<p>Another approach might be to work with your original bucket design but with non-uniform buckets whose indexes themselves are randomly sampled:</p>

<pre><code>import random

def samplegen(start, end, sample_size):
    random_bucket_indices = random.sample(range(start, end), sample_size)
    sorted_bucket_indices = sorted(random_bucket_indices) + [end + 1]
    for index in random_bucket_indices:
        yield random.randrange(index, sorted_bucket_indices[sorted_bucket_indices.index(index) + 1])
</code></pre>

python random