May I loop over a changing list?

Olaf Delgado delgado at Mathematik.Uni-Bielefeld.DE
Wed Sep 22 11:41:50 EDT 1999


On Wed, 22 Sep 1999, Skip Montanaro wrote:

> 
>     > Olaf Delgado writes:
>     >> I am whondering whether the following is considered good (and,
>     >> more important: save) programming style in python:
> 
>     Charles> No, you must never modify a list your are iterating over.

Thank you, Charles, for mentioning the tutorial! Now I remember having
read that passage once upon a time.

>     for i in range(len(mylist)):
> 	if mylist[i] == "a":
> 	   mylist.append(mylist[i])

That's fine as long as I only want to iterate over the original list.
Otherwise, I'll have to use the while loop from my original posting.
That's fine also. On the other hand, I was told that sequence iteration
(at least for user defined types) works by calling seq.__getitem__(i)
repeatedly for increasing i and seq.__getitem__(i) should be equivalent to
seq[i]. So, if builtin types behave like user-defined ones, the effect of
modifying a list while iterating over it should be completely predictable
and shouldn't be an implementation detail. Of course, the interpreter
might do some clever optimization for builtin types, or there might be
alternative ways to implement for loops in future versions of python.

So, the _real_ question (tm) here is: is the passage in the tutorial a
"Don't do it, it's undefined." or a "Oh no, kiddy, this will confuse your
little mind."?

Cheers,
Olaf





More information about the Python-list mailing list