modifying mutable list elements in a for loop
Peter Hansen
peter at engcorp.com
Wed May 26 21:36:21 EDT 2004
Arthur wrote:
> On Wed, 26 May 2004 09:37:54 -0400, Peter Hansen wrote:
>>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.
>
> OTOH:
>
> d={"a":1,"b":2}
> for k in d:
> d.pop(k)
>
> results in:
>
> RuntimeError: dictionary changed size during iteration
>
> I don't recall why I ran into this. But was mildly surprised.
Interesting, but on second thought quite logical I think.
After all, dictionaries are not *sequences*, so there is
no defined order in which to iterate over their keys, so
changes would have undefined results unless a copy was made
of the keys at the start of the loop. I suspect that
wasn't done because it would waste memory and time and
the only benefit would be allowing in-loop modifications.
Iterating over a sequences, on the other hand, is handled
in a clearly defined fashion and therefore modifications
to the sequence can be done during the loop if that makes
sense (though mostly it doesn't).
-Peter
More information about the Python-list
mailing list