Python -- Iterate an iterator twice
<p><em>Edit: There is a <a href="https://stackoverflow.com/questions/3266180">similar question here</a> that deals with iterator resetting. The accepted answer below however addresses the actual issue of nested iterators, and handles an easy to miss issue, whereby the nested iterator doesn't reset.</em></p>

<p>Is there any way to iterate over an iterator twice in python?</p>

<p>In the example code below I can see that the second iteration is operating on the same object as the first, and thus yields a weird result. Contrast this with the C# below that yields the result I'm after.</p>

<p>Is there any way to do what I want. I was wondering if I could make a copy of the iterator or "retrieve" the function it came from, but maybe there's a simpler way. (I know I could just call <code>MyIter()</code> twice in the toy example below, but that's useless if I don't know where the iterator came from and isn't what I'm after!).</p>

<pre><code>def MyIter():
  yield 1;
  yield 2;
  yield 3;
  yield 4;

def PrintCombos(x):
  for a in x:
      for b in x:
          print(a,"-",b);

PrintCombos(MyIter());
</code></pre>

<p>gives</p>

<pre><code>1 - 2
1 - 3
1 - 4
</code></pre>

<p>Contrast with:</p>

<pre><code>static IEnumerable MyIter()
{
    yield return 1;
    yield return 2;
    yield return 3;
    yield return 4;
}

static void PrintCombos(IEnumerable x)
{
    foreach (var a in x)
        foreach (var b in x)
            Console.WriteLine(a + "-" + b);
}

public static void Main(String[] args)
{
    PrintCombos(MyIter());
}
</code></pre>

<p>Which gives:</p>

<pre><code>1-1
1-2
1-3
1-4
2-1
2-2
. . .
</code></pre>