[Python-checkins] cpython (merge 3.3 -> default): Issue #16225: Merge from 3.3: Add additional note to tutorial about looping.

chris.jerdonek python-checkins at python.org
Tue Oct 16 04:51:39 CEST 2012


http://hg.python.org/cpython/rev/e0a407d41af5
changeset:   79729:e0a407d41af5
parent:      79723:d3c7ebdc71bb
parent:      79728:8cb14494d33c
user:        Chris Jerdonek <chris.jerdonek at gmail.com>
date:        Mon Oct 15 19:47:32 2012 -0700
summary:
  Issue #16225: Merge from 3.3: Add additional note to tutorial about looping.

files:
  Doc/tutorial/controlflow.rst    |  22 ++++++++++----------
  Doc/tutorial/datastructures.rst |  13 ++++++++++++
  2 files changed, 24 insertions(+), 11 deletions(-)


diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst
--- a/Doc/tutorial/controlflow.rst
+++ b/Doc/tutorial/controlflow.rst
@@ -58,24 +58,24 @@
 ::
 
    >>> # 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']
 
 
diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst
--- a/Doc/tutorial/datastructures.rst
+++ b/Doc/tutorial/datastructures.rst
@@ -589,6 +589,19 @@
    orange
    pear
 
+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:
 

-- 
Repository URL: http://hg.python.org/cpython


More information about the Python-checkins mailing list