For a small project I'm working on I need to cycle through a list. For each element of this cycle I have to start another cycle through the same list, with the former element as first element of the new cycle. For example I'd like to be able to produce something like this:
1, 2, 3, 4, 1, 2, 3, 4, 1, ...
2, 3, 4, 1, 2, 3, 4, 1, 2, ...
3, 4, 1, 2, 3, 4, 1, 2, 3, ...
4, 1, 2, 3, 4, 1, 2, 3, 4, ...
1, 2, 3, 4, 1, 2, 3, 4, 1, ...
...
I thought that copying a itertools.cycle after each .next() would conserve the current state, so that I can begin the new cycle with the element from the "outer" cycle. Or even "reset the cycle pointer" to an older position. I tried the following:
>>> import itertools, copy
>>> a = itertools.cycle([1, 2, 3, 4])
>>> b = copy.copy(a)
but got this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.6/copy.py", line 95, in copy
return _reconstruct(x, rv, 0)
File "/usr/lib/python2.6/copy.py", line 323, in _reconstruct
y = callable(*args)
File "/usr/lib/python2.6/copy_reg.py", line 93, in __newobj__
return cls.__new__(cls, *args)
TypeError: cycle expected 1 arguments, got 0
I know there are many different ways to achieve what I want but I'm looking for some short, clear and pythonic code. Maybe someone has another idea or even a snippet? The fact that it's not possible to copy iterator objects woke my interest. Is there a best-practice in situations where one wants a copy of an iterable? Or is copying iterables silly and useless in general?