diff --git a/Doc/tutorial/datastructures.rst b/Doc/tutorial/datastructures.rst --- a/Doc/tutorial/datastructures.rst +++ b/Doc/tutorial/datastructures.rst @@ -589,6 +589,19 @@ orange pear +It is not safe to modify a sequence being iterated over while in the loop. +If you need to modify the list you are iterating over (for example, to +duplicate selected items), you can iterate over a copy and modify the +original. The slice notation makes this particularly convenient:: + + >>> words = ['cat', 'window', 'defenestrate'] + >>> for w in words[:]: # Make a slice copy of the entire list. + ... if len(w) > 6: + ... words.insert(0, w) + ... + >>> words + ['defenestrate', 'cat', 'window', 'defenestrate'] + .. _tut-conditions: