bpo-30826: Improve control flow examples (GH-15407) (GH-15410) · python/cpython@b6341e6 (original) (raw)

`@@ -66,20 +66,20 @@ they appear in the sequence. For example (no pun intended):

`

66

66

` window 6

`

67

67

` defenestrate 12

`

68

68

``

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

`

83

83

``

84

84

``

85

85

`.. _tut-range:

`