iter

Aahz aahz at pythoncraft.com
Tue Aug 24 10:54:45 EDT 2010


In article <mailman.1857.1281373933.1673.python-list at python.org>,
Terry Reedy  <tjreedy at udel.edu> wrote:
>
>Changing a list while iterating through it is possible, sometimes 
>useful, but error prone, especially with insert or delete. Changing a 
>dict while iterating through it is prohibited since the iteration order 
>depends on the exact internal structure. That in turn depends on the 
>history of additions and deletions.

Although I agree in general with your warning, you are factually
incorrect about dicts:

>>> d = {1:2, 3:4}
>>> i = iter(d)
>>> i.next()
1
>>> d[1] = 'foo'
>>> d
{1: 'foo', 3: 4}

Essentially, the prohibition is against changing the *keys* of lists and
dicts (where list keys are the indexes).  So what you can't do is add or
delete dict keys and changing the position or order of list elements is
a Bad Idea.  But changing dict or list values is fine as long as you're
careful that's *all* you're doing.  Python newcomers are best off simply
avoiding any list/dict mutation during iteration.
-- 
Aahz (aahz at pythoncraft.com)           <*>         http://www.pythoncraft.com/

"...if I were on life-support, I'd rather have it run by a Gameboy than a
Windows box."  --Cliff Wells



More information about the Python-list mailing list