string issue

Nick Coghlan ncoghlan at iinet.net.au
Fri Feb 4 22:59:54 EST 2005


rbt wrote:
> Alan McIntyre wrote:
> 
>> I think it's because you're modifying the list as you're iterating 
>> over it.  
> 
> 
> One last clarification on this. It's OK to modify the elements of a 
> list, but not the list itself while iterating over it... is that the 
> correct way to think about this?

Correct - the iteration code bases the iteration on the *old* list structure, so 
you can end up with odd behaviour.

Py> l = range(10)
Py> for i in l: del l[i]
...
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
IndexError: list assignment index out of range
Py> l
[1, 2, 4, 5, 7, 9]

Dictionaries have the same problem, but they include some guards that try to 
detect it:

Py> d = dict.fromkeys(range(10))
Py> for i in d: del d[i]
...
Traceback (most recent call last):
   File "<stdin>", line 1, in ?
RuntimeError: dictionary changed size during iteration

This feature can't be added to lists because it is possible to iterate sensibly 
over a mutating list:

Py> l = range(10)
Py> for i in reversed(l): del l[i]
...
Py> l
[]

Cheers,
Nick.

-- 
Nick Coghlan   |   ncoghlan at email.com   |   Brisbane, Australia
---------------------------------------------------------------
             http://boredomandlaziness.skystorm.net



More information about the Python-list mailing list