Note that there are some explanatory texts on larger screens.

plurals
  1. POPythonic way of copying an iterable object
    primarykey
    data
    text
    <p>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:</p> <pre><code>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, ... ... </code></pre> <p>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:</p> <pre><code>&gt;&gt;&gt; import itertools, copy &gt;&gt;&gt; a = itertools.cycle([1, 2, 3, 4]) &gt;&gt;&gt; b = copy.copy(a) </code></pre> <p>but got this error:</p> <pre><code>Traceback (most recent call last): File "&lt;stdin&gt;", line 1, in &lt;module&gt; 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 </code></pre> <p>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 <a href="http://mail.python.org/pipermail/python-dev/2010-April/099045.html" rel="noreferrer">not possible to copy iterator objects</a> 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?</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload