Skip to content

Commit a09bc3a

Browse files
authored
bpo-46095: Improve SeqIter documentation. (GH-30316)
1 parent ac4eea2 commit a09bc3a

File tree

2 files changed

+10
-21
lines changed

2 files changed

+10
-21
lines changed

Doc/library/stdtypes.rst

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -959,6 +959,16 @@ This means that to compare equal, every element must compare equal and the
959959
two sequences must be of the same type and have the same length. (For full
960960
details see :ref:`comparisons` in the language reference.)
961961

962+
.. index::
963+
single: loop; over mutable sequence
964+
single: mutable sequence; loop over
965+
966+
Forward and reversed iterators over mutable sequences access values using an
967+
index. That index will continue to march forward (or backward) even if the
968+
underlying sequence is mutated. The iterator terminates only when an
969+
:exc:`IndexError` or a :exc:`StopIteration` is encountered (or when the index
970+
drops below zero).
971+
962972
Notes:
963973

964974
(1)

Doc/reference/compound_stmts.rst

Lines changed: 0 additions & 21 deletions
Original file line numberDiff line numberDiff line change
@@ -196,27 +196,6 @@ the built-in function :func:`range` returns an iterator of integers suitable to
196196
emulate the effect of Pascal's ``for i := a to b do``; e.g., ``list(range(3))``
197197
returns the list ``[0, 1, 2]``.
198198

199-
.. note::
200-
201-
.. index::
202-
single: loop; over mutable sequence
203-
single: mutable sequence; loop over
204-
205-
There is a subtlety when the sequence is being modified by the loop (this can
206-
only occur for mutable sequences, e.g. lists). An internal counter is used
207-
to keep track of which item is used next, and this is incremented on each
208-
iteration. When this counter has reached the length of the sequence the loop
209-
terminates. This means that if the suite deletes the current (or a previous)
210-
item from the sequence, the next item will be skipped (since it gets the
211-
index of the current item which has already been treated). Likewise, if the
212-
suite inserts an item in the sequence before the current item, the current
213-
item will be treated again the next time through the loop. This can lead to
214-
nasty bugs that can be avoided by making a temporary copy using a slice of
215-
the whole sequence, e.g., ::
216-
217-
for x in a[:]:
218-
if x < 0: a.remove(x)
219-
220199

221200
.. _try:
222201
.. _except:

0 commit comments

Comments
 (0)