title: How to iterate over a list repeating each element in Python
body: <p>I'm using Python to <strong>infinitely</strong> iterate over a list, repeating each element in the list a number of times. For example given the list:</p>
  
  <pre><code>l = [1, 2, 3, 4]
  </code></pre>
  
  <p>I would like to output each element two times and then repeat the cycle:</p>
  
  <pre><code>1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... 
  </code></pre>
  
  <p>I've got an idea of where to start:</p>
  
  <pre><code>def cycle(iterable):
    if not hasattr(cycle, 'state'):
      cycle.state = itertools.cycle(iterable)
    return cycle.next()
  
   &gt;&gt;&gt; l = [1, 2, 3, 4]
   &gt;&gt;&gt; cycle(l)
   1
   &gt;&gt;&gt; cycle(l)
   2
   &gt;&gt;&gt; cycle(l)
   3
   &gt;&gt;&gt; cycle(l)
   4
   &gt;&gt;&gt; cycle(l)
   1
  </code></pre>
  
  <p>But how would I repeat each element?</p>
  
  <p><strong>Edit</strong></p>
  
  <p>To clarify this should iterate infinitely. Also I've used repeating the element twice as the shortest example -
  <strong>I would really like to repeat each element n times</strong>.</p>
  
  <p><strong>Update</strong></p>
  
  <p>Will your solution lead me to what I was looking for:</p>
  
  <pre><code>&gt;&gt;&gt; import itertools
  &gt;&gt;&gt; def ncycle(iterable, n):
  ...   for item in itertools.cycle(iterable):
  ...     for i in range(n):
  ...       yield item
  &gt;&gt;&gt; a = ncycle([1,2], 2)
  &gt;&gt;&gt; a.next()
  1
  &gt;&gt;&gt; a.next()
  1
  &gt;&gt;&gt; a.next()
  2
  &gt;&gt;&gt; a.next()
  2
  &gt;&gt;&gt; a.next()
  1
  &gt;&gt;&gt; a.next()
  1
  &gt;&gt;&gt; a.next()
  2
  &gt;&gt;&gt; a.next()
  2
  </code></pre>
  
  <p>Thanks for the quick answers!</p>