modifying mutable list elements in a for loop
Arthur
ajsiegel at optonline.com
Wed May 26 20:09:17 EDT 2004
On Wed, 26 May 2004 09:37:54 -0400, Peter Hansen <peter at engcorp.com>
wrote:
>Peter Ballard wrote:
>
>> The python tutorial tells me "It is not safe to modify the sequence
>> being iterated over in the loop". But what if my list elements are
>> mutable, such as lists or objects, e.g.
>
>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.
Art
More information about the Python-list
mailing list