Re: modifying mutable list elements in a for loop

From: Peter Hansen (peter_at_engcorp.com)
Date: 05/27/04


Date: Wed, 26 May 2004 21:36:21 -0400

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



Relevant Pages

  • Re: Generator
    ... following generator function: ... There is a subtlety when the sequence is being modified by the loop ... and this is incremented on each iteration. ...
    (comp.lang.python)
  • Re: "do" as a keyword
    ... all looping constructs could be ... solutions in terms of iteration over sequence rather than as traditional ... If I need a "1 or more" loop I formulate the ... problem as a sequence of 1 or more elements. ...
    (comp.lang.python)
  • Re: collatz proof algorithm reveals e
    ... seen Stopping Time refer to the iteration count from ... numbers in a sequence based on the bit-pattern of n. ... but that sequence will NOT be a Sequence Vector because ... And that brings me to your algorithm. ...
    (sci.math)
  • Re: Steve Summit C Notes {Anticipating the next one}
    ... then recursion or iteration might ... If you just want one value at a specified place in the sequence, ... but solves the problem in a general sense. ...
    (comp.lang.c)
  • Re: A tiny Collatz-exercise
    ... as one single step, and consider Cfor odd x only. ... This sequence is strictly increasing, which is obvious, ... bit per iteration. ... which doesn't take certain realities of the Collatz ...
    (sci.math)