Skip to content

Instantly share code, notes, and snippets.

@sohang3112
Created January 27, 2026 15:27
Show Gist options
  • Select an option

  • Save sohang3112/e8de50a56dbd28a3bf7bd1f61bae1e8b to your computer and use it in GitHub Desktop.

Select an option

Save sohang3112/e8de50a56dbd28a3bf7bd1f61bae1e8b to your computer and use it in GitHub Desktop.
Implementing tee() function of itertools
def tee(it):
it = iter(it)
cache = []
counts = [0,0]
class _Iterator:
def __init__(self, i, j):
self.i = i
self.j = j
def __iter__(self):
return self
def __next__(self):
counts[self.i] += 1
if counts[self.i] < counts[self.j]:
return cache.pop(0)
else:
cache.append(next(it))
return cache[-1]
return _Iterator(0,1), _Iterator(1,0)
# Usage Example
a, b = tee(range(20))
print('a', next(a))
print('a', next(a))
print('a', next(a))
print('b', next(b))
print(list(a), list(b))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment