Skip to content

Instantly share code, notes, and snippets.

@mesejo
Created October 11, 2025 13:27
Show Gist options
  • Save mesejo/1946cd047c772dcc1ff050a8f763ad4d to your computer and use it in GitHub Desktop.
Save mesejo/1946cd047c772dcc1ff050a8f763ad4d to your computer and use it in GitHub Desktop.
Reusable Iterator
from itertools import count
counter = count()
def copy_iterator(iterable, lst):
for item in lst:
yield item
added = len(lst)
for item in iterable:
lst.append(item)
added += 1
yield item
# iterate over the rest
for item in lst[added:]:
yield item
class ReusableIterator:
def __init__(self, iterator):
self.iterator = iter(iterator)
self.accumulator = []
def __iter__(self):
return copy_iterator(self.iterator, self.accumulator)
@classmethod
def from_iterator(cls, iterator):
return cls(iterator)
iterator = range(10)
r = ReusableIterator.from_iterator(iterator)
for item in r:
for i2 in r:
for i3 in r:
print(item, i2, i3)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment