summaryrefslogtreecommitdiffstats
path: root/Doc
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2024-05-05 06:42:30 (GMT)
committerGitHub <noreply@github.com>2024-05-05 06:42:30 (GMT)
commitc7c9b913c01afb8d2ff4048f82155969f7ef75b1 (patch)
treefdf8690ec95c0c18a55d0dc9ac70777a46ae9e04 /Doc
parentfd0ea63f82bf9b8f766ea40cfa5befa653461e8a (diff)
downloadcpython-c7c9b913c01afb8d2ff4048f82155969f7ef75b1.zip
cpython-c7c9b913c01afb8d2ff4048f82155969f7ef75b1.tar.gz
cpython-c7c9b913c01afb8d2ff4048f82155969f7ef75b1.tar.bz2
gh-118476: Fix corner cases in islice() rough equivalent. (Gh-118559)
Diffstat (limited to 'Doc')
-rw-r--r--Doc/library/itertools.rst29
1 files changed, 11 insertions, 18 deletions
diff --git a/Doc/library/itertools.rst b/Doc/library/itertools.rst
index 8209060..fb3f333 100644
--- a/Doc/library/itertools.rst
+++ b/Doc/library/itertools.rst
@@ -504,24 +504,17 @@ loops that truncate the stream.
# islice('ABCDEFG', 2, None) → C D E F G
# islice('ABCDEFG', 0, None, 2) → A C E G
s = slice(*args)
- start, stop, step = s.start or 0, s.stop or sys.maxsize, s.step or 1
- it = iter(range(start, stop, step))
- try:
- nexti = next(it)
- except StopIteration:
- # Consume *iterable* up to the *start* position.
- for i, element in zip(range(start), iterable):
- pass
- return
- try:
- for i, element in enumerate(iterable):
- if i == nexti:
- yield element
- nexti = next(it)
- except StopIteration:
- # Consume to *stop*.
- for i, element in zip(range(i + 1, stop), iterable):
- pass
+ start = 0 if s.start is None else s.start
+ stop = s.stop
+ step = 1 if s.step is None else s.step
+ if start < 0 or (stop is not None and stop < 0) or step <= 0:
+ raise ValueError
+ indices = count() if stop is None else range(max(stop, start))
+ next_i = start
+ for i, element in zip(indices, iterable):
+ if i == next_i:
+ yield element
+ next_i += step
.. function:: pairwise(iterable)