bpo-30826: Improve control flow examples (GH-15407) (GH-15410)

(cherry picked from commit 6fcb6cfb13)

Co-authored-by: Raymond Hettinger <rhettinger@users.noreply.github.com>
This commit is contained in:
Miss Islington (bot) 2019-08-22 23:52:12 -07:00 committed by Raymond Hettinger
parent f6a7f5bc50
commit b6341e676a

View file

@ -66,20 +66,20 @@ they appear in the sequence. For example (no pun intended):
window 6 window 6
defenestrate 12 defenestrate 12
If you need to modify the sequence you are iterating over while inside the loop Code that modifies a collection while iterating over that same collection can
(for example to duplicate selected items), it is recommended that you first be tricky to get right. Instead, it is usually more straight-forward to loop
make a copy. Iterating over a sequence does not implicitly make a copy. The over a copy of the collection or to create a new collection::
slice notation makes this especially convenient::
>>> for w in words[:]: # Loop over a slice copy of the entire list. # Strategy: Iterate over a copy
... if len(w) > 6: for user, status in users.copy().items():
... words.insert(0, w) if status == 'inactive':
... del users[user]
>>> words
['defenestrate', 'cat', 'window', 'defenestrate']
With ``for w in words:``, the example would attempt to create an infinite list, # Strategy: Create a new collection
inserting ``defenestrate`` over and over again. active_users = {}
for user, status in users.items():
if status == 'active':
active_users[user] = status
.. _tut-range: .. _tut-range: