[Tutor] For loop breaking string methods

bob gailer bgailer at gmail.com
Tue Apr 27 16:10:27 CEST 2010

On 4/26/2010 10:19 PM, Dave Angel wrote:
> Note also that if you insert or delete from the list while you're 
> looping, you can get undefined results.

The results are not undefined. They m,ight be unexpected, but that is 
due to an invalid assumption.

The behavior is explained in section 7.3 of The Python Language 
Reference. Note especially:


There is a subtlety when the sequence is being modified by the loop 
(this can only occur for mutable sequences, i.e. lists). An internal 
counter is used to keep track of which item is used next, and this is 
incremented on each iteration. When this counter has reached the length 
of the sequence the loop terminates. This means that if the suite 
deletes the current (or a previous) item from the sequence, the next 
item will be skipped (since it gets the index of the current item which 
has already been treated). Likewise, if the suite inserts an item in the 
sequence before the current item, the current item will be treated again 
the next time through the loop. This can lead to nasty bugs that can be 
avoided by making a temporary copy using a slice of the whole sequence, 

for  x  in  a[:]:
     if  x  <  0:  a.remove(x)

Bob Gailer
Chapel Hill NC

More information about the Tutor mailing list