for i in list - change a list inside a for loop?

Alex Martelli aleax at aleax.it
Sat Mar 1 23:33:17 CET 2003


Klaus Meyer wrote:

>> Better read about it in the Language Reference,
>> http://www.python.org/doc/current/ref/for.html
> 
> Example:
> 
> x=range(10)
> for i in x:
> x.append(i)
> 
> Hm, the ref says:
> The expression list is evaluated once

It is evaluated once, and it gives an object -- a mutable
object.  Name x refers to just the same object, of course.

> If this was true, shouldn't the example stop after 10 loops?

It would, if you didn't mutate the object.

> But this gives a nice endless loop and a growing and growing x ....

Because you DO mutate the object x on which you're looping.

> My example was a simplification. In real i need re and something else so i
> must iterate over all elements.
> 
> I think i make a new list similarly to that example, that Anton gave. This
> would be a clean solution, i think.

Yes, Python does not make copies implicitly: when you want a copy
you ask for one.  There are many ways to ask for a copy, e.g.:

for i in list(x): x.append(i)

import copy
for i in copy.copy(x): x.append(i)

for i in x[:]: x.append(i)

for i in [i for i in x]: x.append(i)

My favourite is copy.copy(x), closely followed by list(x); I think these
are very readable and explicit, while the others are more mysterious.


Alex





More information about the Python-list mailing list