Skip to content

Commit c7c9b91

Browse files
authored
gh-118476: Fix corner cases in islice() rough equivalent. (Gh-118559)
1 parent fd0ea63 commit c7c9b91

File tree

1 file changed

+11
-18
lines changed

1 file changed

+11
-18
lines changed

Doc/library/itertools.rst

Lines changed: 11 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -504,24 +504,17 @@ loops that truncate the stream.
504504
# islice('ABCDEFG', 2, None) → C D E F G
505505
# islice('ABCDEFG', 0, None, 2) → A C E G
506506
s = slice(*args)
507-
start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
508-
it = iter(range(start, stop, step))
509-
try:
510-
nexti = next(it)
511-
except StopIteration:
512-
# Consume *iterable* up to the *start* position.
513-
for i, element in zip(range(start), iterable):
514-
pass
515-
return
516-
try:
517-
for i, element in enumerate(iterable):
518-
if i == nexti:
519-
yield element
520-
nexti = next(it)
521-
except StopIteration:
522-
# Consume to *stop*.
523-
for i, element in zip(range(i + 1, stop), iterable):
524-
pass
507+
start = 0 if s.start is None else s.start
508+
stop = s.stop
509+
step = 1 if s.step is None else s.step
510+
if start < 0 or (stop is not None and stop < 0) or step <= 0:
511+
raise ValueError
512+
indices = count() if stop is None else range(max(stop, start))
513+
next_i = start
514+
for i, element in zip(indices, iterable):
515+
if i == next_i:
516+
yield element
517+
next_i += step
525518

526519

527520
.. function:: pairwise(iterable)

0 commit comments

Comments
 (0)