Created
January 27, 2026 15:27
-
-
Save sohang3112/e8de50a56dbd28a3bf7bd1f61bae1e8b to your computer and use it in GitHub Desktop.
Implementing tee() function of itertools
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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