python repeat list elements in an iterator
<p>Is there any way to create an iterator to repeat elements in a list certain times? For example, a list is given:</p>

<pre><code>color = ['r', 'g', 'b']
</code></pre>

<p>Is there a way to create a iterator in form of <code>itertools.repeatlist(color, 7)</code> that can produce the following list?</p>

<pre><code>color_list = ['r', 'g', 'b', 'r', 'g', 'b', 'r']
</code></pre>

<p>You can use <a href="https://docs.python.org/2/library/itertools.html#itertools.cycle"><code>itertools.cycle()</code></a> together with <a href="https://docs.python.org/2/library/itertools.html#itertools.islice"><code>itertools.islice()</code></a> to build your <code>repeatlist()</code> function:</p>

<pre><code>from itertools import cycle, islice

def repeatlist(it, count):
    return islice(cycle(it), count)
</code></pre>

<p>This returns a new iterator; call <code>list()</code> on it if you must have a list object.</p>

<p>Demo:</p>

<pre><code>&gt;&gt;&gt; from itertools import cycle, islice
&gt;&gt;&gt; def repeatlist(it, count):
...     return islice(cycle(it), count)
...
&gt;&gt;&gt; color = ['r', 'g', 'b']
&gt;&gt;&gt; list(repeatlist(color, 7))
['r', 'g', 'b', 'r', 'g', 'b', 'r']
</code></pre>

python itertools