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>Since you commented that the order doesn't matter (I had asked whether it must be random or can be sorted), this might be an option:</p>

<pre><code>import random

def sample(n, k):
    """Generate random sorted k-sample of range(n)."""
    for i in range(n):
        if random.randrange(n - i) &lt; k:
            yield i
            k -= 1
</code></pre>

<p>That goes through the numbers and includes each in the sample with probability<br>
numberOfNumbersStillNeeded / numberOfNumbersStillLeft.</p>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; for _ in range(5):
        print(list(sample(100, 10)))

[7, 16, 41, 50, 55, 56, 61, 76, 89, 96]
[5, 13, 24, 28, 34, 35, 40, 64, 80, 95]
[9, 18, 19, 36, 38, 39, 61, 73, 84, 85]
[23, 24, 26, 28, 40, 53, 62, 76, 77, 91]
[2, 12, 21, 41, 60, 68, 70, 72, 90, 91]
</code></pre>

python random