modifying mutable list elements in a for loop

Terry Reedy tjreedy at udel.edu
Wed May 26 12:04:27 EDT 2004


"Peter Ballard" <pballard at ozemail.com.au> wrote in message
news:9d5509fa.0405260439.175797e at posting.google.com...
> The python tutorial tells me "It is not safe to modify the sequence
> being iterated over in the loop".

What is not safe *in general* is adding and subtracting items to and from
the list while traversing it, either directly or indirectly (via an index
variable).  There are exceptions, but they may or may not be
implementation dependent (I would have to read the standard more closely to
say more), and should only be used by people who understand them.

What is safe is modifying or replacing the 'current' item.  The former is
easy.  The latter requires the item index, as in 'for i in range(l): l[i] =
f(l[i])' (in-place map) -- but here, the iteration list isnt the list being
modified! (nor is it with enumerate()!)

Terry J. Reedy







More information about the Python-list mailing list