Simple question about mutable container iterator

Diez B. Roggisch deetsNOSPAM at web.de
Thu Apr 22 10:19:23 EDT 2004


Neal D. Becker wrote:

> x = [1,2,3]
> 
> for i in x:
>   i = 2
> 
> This doesn't change x.  2 questions:
> 
> 1) Why not?  Why doesn't assign to an iterator of a mutable type change
> the underlying object?

because i doesn't point to an iterator, but instead to the value. The line

i = 2

rebinds i to the value 2 - which doesn't affect the list x.

In python, an iterator has only a next()-method. So its immutable and only
capable of delivering the values in the order they appear in the underlying 
collection. 

> 2) What is the preferred way to do this?

For lists, you could do


for index, v in enumerate(x):
   x[index] = 2


-- 
Regards,

Diez B. Roggisch



More information about the Python-list mailing list