Unexpected Behavior Iterating over a Mutating Object

bruno modulix onurb at xiludom.gro
Wed Sep 14 05:12:14 EDT 2005


Dave Hansen wrote:
(snip code snippets and sensible explanations)

> Again, iterating over an item that is mutating seems like a Bad
> Idea(tm) to me.  

It as *always* been a bad idea to modify a list in place (I mean adding
or removing items) while iterating over it, whatever the language. If
you *really* need to do such a thing (for effeciency reasons - and then
it's usually in low-level C code), you'd better use indexed access, and
adjust the index as needed - but this results in tricky, hard to
maintain code.

> But I was curious: is this the intended behavior, or
> does this fall under what C programmers would call 'undefined
> behavior.'

Not being a Language Lawyer(tm), I can't tell for sure, but I'd think
it's the expected behavior. Anyway it's not a behavior I'd relie upon,
since it would be too much of a dirty trick anyway.

My 2 cents
-- 
bruno desthuilliers
python -c "print '@'.join(['.'.join([w[::-1] for w in p.split('.')]) for
p in 'onurb at xiludom.gro'.split('@')])"



More information about the Python-list mailing list