modifying mutable list elements in a for loop

Michael Chermside mcherm at mcherm.com
Wed May 26 09:17:49 EDT 2004


Peter Ballard writes:
> The python tutorial tells me "It is not safe to modify the sequence
> being iterated over in the loop".
 [... tried modifying the list elements and it worked ...]
> because how else can one perform an operation on a list of objects?
> But that phrase "It is not safe to modify the sequence being iterated
> over in the loop" in the tutorial has me slightly worried.

Actually, you're far more worried than necessary. The Python tutorial
is written for beginners, and the stricture to avoid modifying a
sequence being iterated over is good advice for beginners, rather
than an actual rule of the Python language.

First of all, your analysis is correct: it is always OK to modify the
items in a list during a loop. You are even correct that what the
list "really" contains (at the C level) is just pointers to the items
in the list.

But the real truth goes even further. There are some data structures
in some languages which you *MUST NOT* modify while traversing them
because for some reason (probably having to do with threading) it
would result in undefined behavior. But that is NOT a problem with
Python. In Python it's perfectly OK to modify a list (or dict, or
whatever) while traversing it, it's just not a good idea for
beginners (or experienced programmers who want to produce
understandable code) because the behavior may not be what you expect.

    >>> alist = range(10)
    >>> for x in alist:
    ...     alist.remove(x)
    ...
    >>> alist
    [1, 3, 5, 7, 9]

This behavior is perfectly well defined. (Think about it. Now think
about it again. Got it?) But you have to admit that it's confusing
to beginners, so the Tutorial strongly recomends against it.

-- Michael Chermside






More information about the Python-list mailing list