]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
Issue #16225: Backport from 3.2: Add additional note to tutorial about looping.
authorChris Jerdonek <chris.jerdonek@gmail.com>
Tue, 16 Oct 2012 03:01:38 +0000 (20:01 -0700)
committerChris Jerdonek <chris.jerdonek@gmail.com>
Tue, 16 Oct 2012 03:01:38 +0000 (20:01 -0700)
Doc/tutorial/controlflow.rst
Doc/tutorial/datastructures.rst

index 3d3af4e9374966d027b9810261cce492da45b667..e0ee46bbe8bb618571b64110c5b7e0d0be3ee8d7 100644 (file)
@@ -59,24 +59,24 @@ they appear in the sequence.  For example (no pun intended):
 ::
 
    >>> # Measure some strings:
-   ... a = ['cat', 'window', 'defenestrate']
-   >>> for x in a:
-   ...     print x, len(x)
+   ... words = ['cat', 'window', 'defenestrate']
+   >>> for w in words:
+   ...     print w, len(w)
    ...
    cat 3
    window 6
    defenestrate 12
 
-It is not safe to modify the sequence being iterated over in the loop (this can
-only happen for mutable sequence types, such as lists).  If you need to modify
-the list you are iterating over (for example, to duplicate selected items) you
-must iterate over a copy.  The slice notation makes this particularly
-convenient::
+If you need to modify the sequence you are iterating over while inside the loop
+(for example to duplicate selected items), it is recommended that you first
+make a copy.  Iterating over a sequence does not implicitly make a copy.  The
+slice notation makes this especially convenient::
 
-   >>> for x in a[:]: # make a slice copy of the entire list
-   ...    if len(x) > 6: a.insert(0, x)
+   >>> for w in words[:]:  # Loop over a slice copy of the entire list.
+   ...     if len(w) > 6:
+   ...         words.insert(0, w)
    ...
-   >>> a
+   >>> words
    ['defenestrate', 'cat', 'window', 'defenestrate']
 
 
index f55674e8fd4f9ea99066f14ac9159bd03ea8e218..88ab372960286b17c615a8815c2890b3cf9c5a48 100644 (file)
@@ -645,6 +645,19 @@ retrieved at the same time using the :meth:`iteritems` method. ::
    gallahad the pure
    robin the brave
 
+To change a sequence you are iterating over while inside the loop (for
+example to duplicate certain items), it is recommended that you first make
+a copy.  Looping over a sequence does not implicitly make a copy.  The slice
+notation makes this especially convenient::
+
+   >>> words = ['cat', 'window', 'defenestrate']
+   >>> for w in words[:]:  # Loop over a slice copy of the entire list.
+   ...     if len(w) > 6:
+   ...         words.insert(0, w)
+   ...
+   >>> words
+   ['defenestrate', 'cat', 'window', 'defenestrate']
+
 
 .. _tut-conditions: