Skip to content

Commit 68316a0

Browse files
[3.12] gh-118476: Fix corner cases in islice() rough equivalent. (Gh-118559) (#118587)
1 parent d629819 commit 68316a0

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
@@ -496,24 +496,17 @@ loops that truncate the stream.
496496
# islice('ABCDEFG', 2, None) → C D E F G
497497
# islice('ABCDEFG', 0, None, 2) → A C E G
498498
s = slice(*args)
499-
start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
500-
it = iter(range(start, stop, step))
501-
try:
502-
nexti = next(it)
503-
except StopIteration:
504-
# Consume *iterable* up to the *start* position.
505-
for i, element in zip(range(start), iterable):
506-
pass
507-
return
508-
try:
509-
for i, element in enumerate(iterable):
510-
if i == nexti:
511-
yield element
512-
nexti = next(it)
513-
except StopIteration:
514-
# Consume to *stop*.
515-
for i, element in zip(range(i + 1, stop), iterable):
516-
pass
499+
start = 0 if s.start is None else s.start
500+
stop = s.stop
501+
step = 1 if s.step is None else s.step
502+
if start < 0 or (stop is not None and stop < 0) or step <= 0:
503+
raise ValueError
504+
indices = count() if stop is None else range(max(stop, start))
505+
next_i = start
506+
for i, element in zip(indices, iterable):
507+
if i == next_i:
508+
yield element
509+
next_i += step
517510

518511

519512
.. function:: pairwise(iterable)

0 commit comments

Comments
 (0)