Skip to content

Commit 6fcb6cf

Browse files
authored
bpo-30826: Improve control flow examples (GH-15407)
1 parent 483ae0c commit 6fcb6cf

File tree

1 file changed

+14
-14
lines changed

1 file changed

+14
-14
lines changed

Doc/tutorial/controlflow.rst

Lines changed: 14 additions & 14 deletions
Original file line numberDiff line numberDiff line change
@@ -66,20 +66,20 @@ they appear in the sequence. For example (no pun intended):
6666
window 6
6767
defenestrate 12
6868

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::
73-
74-
>>> for w in words[:]: # Loop over a slice copy of the entire list.
75-
... if len(w) > 6:
76-
... words.insert(0, w)
77-
...
78-
>>> words
79-
['defenestrate', 'cat', 'window', 'defenestrate']
80-
81-
With ``for w in words:``, the example would attempt to create an infinite list,
82-
inserting ``defenestrate`` over and over again.
69+
Code that modifies a collection while iterating over that same collection can
70+
be tricky to get right. Instead, it is usually more straight-forward to loop
71+
over a copy of the collection or to create a new collection::
72+
73+
# Strategy: Iterate over a copy
74+
for user, status in users.copy().items():
75+
if status == 'inactive':
76+
del users[user]
77+
78+
# Strategy: Create a new collection
79+
active_users = {}
80+
for user, status in users.items():
81+
if status == 'active':
82+
active_users[user] = status
8383

8484

8585
.. _tut-range:

0 commit comments

Comments
 (0)