Skip to content

Commit 3147b04

Browse files
authored
bpo-31270: Modification of Pr 3200 (#3427)
* bpo-31270: Simplify documentation of itertools.zip_longest * Use repeat(). Track num_active.
1 parent 0c72a0c commit 3147b04

File tree

1 file changed

+18
-19
lines changed

1 file changed

+18
-19
lines changed

Doc/library/itertools.rst

+18-19
Original file line numberDiff line numberDiff line change
@@ -630,26 +630,25 @@ loops that truncate the stream.
630630
iterables are of uneven length, missing values are filled-in with *fillvalue*.
631631
Iteration continues until the longest iterable is exhausted. Roughly equivalent to::
632632

633-
class ZipExhausted(Exception):
634-
pass
635-
636-
def zip_longest(*args, **kwds):
633+
def zip_longest(*args, fillvalue=None):
637634
# zip_longest('ABCD', 'xy', fillvalue='-') --> Ax By C- D-
638-
fillvalue = kwds.get('fillvalue')
639-
counter = len(args) - 1
640-
def sentinel():
641-
nonlocal counter
642-
if not counter:
643-
raise ZipExhausted
644-
counter -= 1
645-
yield fillvalue
646-
fillers = repeat(fillvalue)
647-
iterators = [chain(it, sentinel(), fillers) for it in args]
648-
try:
649-
while iterators:
650-
yield tuple(map(next, iterators))
651-
except ZipExhausted:
652-
pass
635+
iterators = [iter(it) for it in args]
636+
num_active = len(iterators)
637+
if not num_active:
638+
return
639+
while True:
640+
values = []
641+
for i, it in enumerate(iterators):
642+
try:
643+
value = next(it)
644+
except StopIteration:
645+
num_active -= 1
646+
if not num_active:
647+
return
648+
iterators[i] = repeat(fillvalue)
649+
value = fillvalue
650+
values.append(value)
651+
yield tuple(values)
653652

654653
If one of the iterables is potentially infinite, then the :func:`zip_longest`
655654
function should be wrapped with something that limits the number of calls

0 commit comments

Comments
 (0)