]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
bpo-46095: Improve SeqIter documentation. (GH-30316) (GH-30330)
authorMiss Islington (bot) <31488909+miss-islington@users.noreply.github.com>
Sat, 1 Jan 2022 19:12:43 +0000 (11:12 -0800)
committerGitHub <noreply@github.com>
Sat, 1 Jan 2022 19:12:43 +0000 (11:12 -0800)
Doc/library/stdtypes.rst
Doc/reference/compound_stmts.rst

index 101bbca7be8b2075030fea6e75db45d9bec67589..8fa252b04d70681a7a353b579657485a8a8711be 100644 (file)
@@ -921,6 +921,16 @@ This means that to compare equal, every element must compare equal and the
 two sequences must be of the same type and have the same length.  (For full
 details see :ref:`comparisons` in the language reference.)
 
+.. index::
+   single: loop; over mutable sequence
+   single: mutable sequence; loop over
+
+Forward and reversed iterators over mutable sequences access values using an
+index.  That index will continue to march forward (or backward) even if the
+underlying sequence is mutated.  The iterator terminates only when an
+:exc:`IndexError` or a :exc:`StopIteration` is encountered (or when the index
+drops below zero).
+
 Notes:
 
 (1)
index 63d885deae93f0c05e383e3eef67b62d7d8478d6..7f37bb4fdf9c999352bc1711fb36a6329a8bec4b 100644 (file)
@@ -196,27 +196,6 @@ the built-in function :func:`range` returns an iterator of integers suitable to
 emulate the effect of Pascal's ``for i := a to b do``; e.g., ``list(range(3))``
 returns the list ``[0, 1, 2]``.
 
-.. note::
-
-   .. index::
-      single: loop; over mutable sequence
-      single: mutable sequence; loop over
-
-   There is a subtlety when the sequence is being modified by the loop (this can
-   only occur for mutable sequences, e.g. lists).  An internal counter is used
-   to keep track of which item is used next, and this is incremented on each
-   iteration.  When this counter has reached the length of the sequence the loop
-   terminates.  This means that if the suite deletes the current (or a previous)
-   item from the sequence, the next item will be skipped (since it gets the
-   index of the current item which has already been treated).  Likewise, if the
-   suite inserts an item in the sequence before the current item, the current
-   item will be treated again the next time through the loop. This can lead to
-   nasty bugs that can be avoided by making a temporary copy using a slice of
-   the whole sequence, e.g., ::
-
-      for x in a[:]:
-          if x < 0: a.remove(x)
-
 
 .. _try:
 .. _except: