Edit: There is a similar question here 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.
Is there any way to iterate over an iterator twice in python?
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.
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 MyIter()
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!).
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());
gives
1 - 2
1 - 3
1 - 4
Contrast with:
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());
}
Which gives:
1-1
1-2
1-3
1-4
2-1
2-2
. . .
PrintCombos(list(MyIter()))
– Hokusaiitertools.tee
might be what you're looking for. – Gules