I'm using Python to infinitely iterate over a list, repeating each element in the list a number of times. For example given the list:
l = [1, 2, 3, 4]
I would like to output each element two times and then repeat the cycle:
1, 1, 2, 2, 3, 3, 4, 4, 1, 1, 2, 2 ...
I've got an idea of 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 should iterate infinitely. Also I've used repeating the element twice as the shortest example - I would really like to repeat each element n times.
Update
Will your solution 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!