Re: modifying mutable list elements in a for loop
From: Peter Hansen (peter_at_engcorp.com)
Date: 05/27/04
- Next message: Joe Wong: "Re: how to terminate a process on win32?"
- Previous message: Josh Gilbert: "Re: Idea: Python Shorthand (was Re: Why a class when there will only be one instance?"
- In reply to: Arthur: "Re: modifying mutable list elements in a for loop"
- Next in thread: Shalabh Chaturvedi: "Re: modifying mutable list elements in a for loop"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
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
- Next message: Joe Wong: "Re: how to terminate a process on win32?"
- Previous message: Josh Gilbert: "Re: Idea: Python Shorthand (was Re: Why a class when there will only be one instance?"
- In reply to: Arthur: "Re: modifying mutable list elements in a for loop"
- Next in thread: Shalabh Chaturvedi: "Re: modifying mutable list elements in a for loop"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|