How to iterate over a list repeating each item in Python

I use Python to endlessly iterate through a list, repeating each element in a list several times. For example, given a list:

l = [1, 2, 3, 4] 

I would like to output each element twice, and then repeat the loop:

 1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ... 

I have an idea where to start:

 def cycle(iterable): if not hasattr(cycle, 'state'): cycle.state = itertools.cycle(iterable) return cycle.next() >>> l = [1, 2, 3, 4] >>> cycle(l) 1 >>> cycle(l) 2 >>> cycle(l) 3 >>> cycle(l) 4 >>> cycle(l) 1 

But how would I repeat each element?

Edit

To clarify this, you need to iterate endlessly. I also used repeating an element twice as the shortest example - I would really like to repeat each element n times .

Update

Your solution will lead me to what I was looking for:

 >>> import itertools >>> def ncycle(iterable, n): ... for item in itertools.cycle(iterable): ... for i in range(n): ... yield item >>> a = ncycle([1,2], 2) >>> a.next() 1 >>> a.next() 1 >>> a.next() 2 >>> a.next() 2 >>> a.next() 1 >>> a.next() 1 >>> a.next() 2 >>> a.next() 2 

Thanks for the quick answers!

+6
python iterator
source share
7 answers

How about this:

 import itertools def bicycle(iterable, repeat=1): for item in itertools.cycle(iterable): for _ in xrange(repeat): yield item c = bicycle([1,2,3,4], 2) print [c.next() for _ in xrange(10)] 

EDIT: added bishanty's repetition count option and an understanding of Adam Rosenfield 's list .

+13
source share

You can do this with a generator quite easily:

 def cycle(iterable): while True: for item in iterable: yield item yield item x=[1,2,3] c=cycle(x) print [c.next() for i in range(10)] // prints out [1,1,2,2,3,3,1,1,2,2] 
+6
source share

The solution should be something like

 iterable = [1, 2, 3, 4] n = 2 while (True): for elem in iterable: for dummy in range(n): print elem # or call function, or whatever 

Edit: Added 'While (True)' to iterate endlessly.

+1
source share
 import itertools as it def ncycle(iterable, n=1): if n == 1: return it.cycle(iterable) return it.cycle(it.chain(*it.izip(*([iterable]*n)))) 
+1
source share
 [ "%d, %d" % (i, i) for i in [1, 2, 3, 4] * 4] 

The last 4 numbers of cycles.

0
source share
 itertools.chain.from_iterable(itertools.repeat(item, repeat) for item in itertools.cycle(l)) 
0
source share

I do this:

 from itertools import cycle, repeat, chain flatten = chain.from_iterable # better name def ncycle(xs, n): return flatten(repeat(x, n) for x in cycle(xs)) # example for n,x in enumerate(ncycle('abcd', 2)): print(x, end=" ") if n > 9: print("") break # output: aabbccddaab 
0
source share

All Articles