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!