Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 38049bb

Browse files
committed
Issue #16225: Merge from 3.2: Add additional note to tutorial about looping.
2 parents 39b8670 + 4fab8f0 commit 38049bb

2 files changed

Lines changed: 24 additions & 11 deletions

File tree

Doc/tutorial/controlflow.rst

Lines changed: 11 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -58,24 +58,24 @@ they appear in the sequence. For example (no pun intended):
5858
::
5959

6060
>>> # Measure some strings:
61-
... a = ['cat', 'window', 'defenestrate']
62-
>>> for x in a:
63-
... print(x, len(x))
61+
... words = ['cat', 'window', 'defenestrate']
62+
>>> for w in words:
63+
... print(w, len(w))
6464
...
6565
cat 3
6666
window 6
6767
defenestrate 12
6868

69-
It is not safe to modify the sequence being iterated over in the loop (this can
70-
only happen for mutable sequence types, such as lists). If you need to modify
71-
the list you are iterating over (for example, to duplicate selected items) you
72-
must iterate over a copy. The slice notation makes this particularly
73-
convenient::
69+
If you need to modify the sequence you are iterating over while inside the loop
70+
(for example to duplicate selected items), it is recommended that you first
71+
make a copy. Iterating over a sequence does not implicitly make a copy. The
72+
slice notation makes this especially convenient::
7473

75-
>>> for x in a[:]: # make a slice copy of the entire list
76-
... if len(x) > 6: a.insert(0, x)
74+
>>> for w in words[:]: # Loop over a slice copy of the entire list.
75+
... if len(w) > 6:
76+
... words.insert(0, w)
7777
...
78-
>>> a
78+
>>> words
7979
['defenestrate', 'cat', 'window', 'defenestrate']
8080

8181

Doc/tutorial/datastructures.rst

Lines changed: 13 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -589,6 +589,19 @@ returns a new sorted list while leaving the source unaltered. ::
589589
orange
590590
pear
591591

592+
To change a sequence you are iterating over while inside the loop (for
593+
example to duplicate certain items), it is recommended that you first make
594+
a copy. Looping over a sequence does not implicitly make a copy. The slice
595+
notation makes this especially convenient::
596+
597+
>>> words = ['cat', 'window', 'defenestrate']
598+
>>> for w in words[:]: # Loop over a slice copy of the entire list.
599+
... if len(w) > 6:
600+
... words.insert(0, w)
601+
...
602+
>>> words
603+
['defenestrate', 'cat', 'window', 'defenestrate']
604+
592605

593606
.. _tut-conditions:
594607

0 commit comments

Comments
 (0)