Random and Itertools
<p>I have some sample code that iterates through two different ranges of numbers successfully, but I want to add functionality to it so that it moves through the chained ranges randomly like so:</p>

<pre><code>import itertools
import random

for f in random.sample(itertools.chain(range(30, 54), range(1, 24)), 48):

    print f
</code></pre>

<p>However this produces the following error:</p>

<pre><code>Traceback (most recent call last):
  File "&lt;pyshell#12&gt;", line 1, in &lt;module&gt;
    for f in random.sample(itertools.chain(range(30, 54), range(1, 24)), 48):
  File "G:\Python27\lib\random.py", line 321, in sample
    n = len(population)
TypeError: object of type 'itertools.chain' has no len()
</code></pre>

<p>Can anyone advise the amendments needed to make this function as intended?</p>

<p>The issue is that <code>itertools.chain</code> creates <a class='doc-link' href="http://stackoverflow.com/documentation/python/292/generators#t=201610111555299054924">generators</a>, rather than lists. These generators are lazily evaluated, each element exists only briefly and is discarded after use.  The <code>len</code> function is not defined for generators because all the elements don't exist at once.</p>

<p>To fix your issue, you'll have to explicitly convert the chain output to a list. </p>

<pre><code>c = itertools.chain(range(30, 54), range(1, 24))
for f in random.sample(list(c), 48):
</code></pre>

python random itertools sample