I want to make a shallow copy of an itertools.cycle object, but I don't know how because it has no builtin copy method. I want to achieve something like the following, where I create a copy of the cycle, iterate through it a few times, then copy the original again, and iterate a few more times starting from the beginning of the cycle.
c = "ABCD"
cyc = itertools.cycle(c)
cyc_copy = cyc.copy()
for i in range(2):
print(next(cyc_copy))
cyc_copy = cyc.copy()
for i in range(2):
print(next(cyc_copy))
> A
B
A
B
It may require some refactoring, but a factory would work well here.
from itertools import cycle
cycle_factory = lambda: cycle('1234')
c1 = cycle_factory()
print next(c1) # 1
c2 = cycle_factory()
print next(c2) # 1
Otherwise, I'm not sure you're going to be able to satisfy the criteria of starting at the beginning of the cycle each time. The class-based approached will also work, but requires a lot more overhead.
One of the issues with the itertools.tee approach is that it will resume iteration where the tee-d iterator left off instead of starting from the beginning. Thus, you have to tee it at the beginning. This may be the only option if you do not have control over how the cycle is generated.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With