Skip to content

Commit

Permalink
Minor improvements to the docs for itertools.tee() (gh-119135)
Browse files Browse the repository at this point in the history
(cherry picked from commit 81c3130)

Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
  • Loading branch information
rhettinger authored and miss-islington committed May 18, 2024
1 parent fa359df commit 525e7ef
Showing 1 changed file with 11 additions and 10 deletions.
21 changes: 11 additions & 10 deletions Doc/library/itertools.rst
Original file line number Diff line number Diff line change
Expand Up @@ -690,18 +690,19 @@ loops that truncate the stream.

def tee(iterable, n=2):
iterator = iter(iterable)
empty_link = [None, None] # Singly linked list: [value, link]
return tuple(_tee(iterator, empty_link) for _ in range(n))
shared_link = [None, None]
return tuple(_tee(iterator, shared_link) for _ in range(n))

def _tee(iterator, link):
while True:
if link[1] is None:
try:
link[:] = [next(iterator), [None, None]]
except StopIteration:
return
value, link = link
yield value
try:
while True:
if link[1] is None:
link[0] = next(iterator)
link[1] = [None, None]
value, link = link
yield value
except StopIteration:
return

Once a :func:`tee` has been created, the original *iterable* should not be
used anywhere else; otherwise, the *iterable* could get advanced without
Expand Down

0 comments on commit 525e7ef

Please sign in to comment.