modifying mutable list elements in a for loop

Peter Hansen peter at engcorp.com
Wed May 26 09:37:54 EDT 2004


Peter Ballard wrote:

> The python tutorial tells me "It is not safe to modify the sequence
> being iterated over in the loop". But what if my list elements are
> mutable, such as lists or objects, e.g.

Treat that as "not safe if you don't know what you are doing".
David's answer is on the mark, but furthermore you *can* modify
the sequence being iterated over, if that's really what you
want to do.  Some algorithms can probably even benefit from the
technique, though I can't think of anything off-hand.

As with many things in Python, consenting adults can do what they
want, and the tutorial is just giving a necessary warning since
many beginners, and even non-beginners from time to time, will be
caught by this problem otherwise.

> [It seems to me that the list elements are pointers (in C-speak), so I
> can safely modify the data they are pointing to, because I am not
> modifying the list elements themselves. Or is that an implementation
> detail (i.e. not safe)?]

It's safe.  And around here they're usually called "references" instead
of "pointers".

> But that phrase "It is not safe to modify the sequence being iterated
> over in the loop" in the tutorial has me slightly worried.

Good. ;-)  Then you'll have to pause and think about it from time to
time as you learn, until you've integrated the knowledge so deeply
that you automatically do the right thing when iterating over lists.
That's the goal of that warning in the tutorial (if I may channel the
author for a moment :-).

-Peter



More information about the Python-list mailing list