summaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorRaymond Hettinger <rhettinger@users.noreply.github.com>2019-08-23 06:44:19 (GMT)
committerGitHub <noreply@github.com>2019-08-23 06:44:19 (GMT)
commit6fcb6cfb139ade1aac6dbee0b18ca72b18cbe0d2 (patch)
tree0cc3a9563bac31ef473e1da450f43992bea62af5
parent483ae0cf1dcf46f8b71c4bf32419dd138e908553 (diff)
downloadcpython-6fcb6cfb139ade1aac6dbee0b18ca72b18cbe0d2.zip
cpython-6fcb6cfb139ade1aac6dbee0b18ca72b18cbe0d2.tar.gz
cpython-6fcb6cfb139ade1aac6dbee0b18ca72b18cbe0d2.tar.bz2
bpo-30826: Improve control flow examples (GH-15407)
-rw-r--r--Doc/tutorial/controlflow.rst28
1 files changed, 14 insertions, 14 deletions
diff --git a/Doc/tutorial/controlflow.rst b/Doc/tutorial/controlflow.rst
index 92c042e..b7e003c 100644
--- a/Doc/tutorial/controlflow.rst
+++ b/Doc/tutorial/controlflow.rst
@@ -66,20 +66,20 @@ they appear in the sequence. For example (no pun intended):
window 6
defenestrate 12
-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 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']
-
-With ``for w in words:``, the example would attempt to create an infinite list,
-inserting ``defenestrate`` over and over again.
+Code that modifies a collection while iterating over that same collection can
+be tricky to get right. Instead, it is usually more straight-forward to loop
+over a copy of the collection or to create a new collection::
+
+ # Strategy: Iterate over a copy
+ for user, status in users.copy().items():
+ if status == 'inactive':
+ del users[user]
+
+ # Strategy: Create a new collection
+ active_users = {}
+ for user, status in users.items():
+ if status == 'active':
+ active_users[user] = status
.. _tut-range: