Simple question about mutable container iterator

Terry Reedy tjreedy at udel.edu
Thu Apr 22 11:42:47 EDT 2004


"Neal D. Becker" <ndbecker2 at verizon.net> wrote in message
news:c68iet$8qd$1 at sea.gmane.org...
> x = [1,2,3]
>
> for i in x:
>   i = 2
>
> This doesn't change x.  2 questions:
>
> 1) Why not?

Why would it?  You are just rebinding the name 'i' to the int 2, over and
over.

> Why doesn't assign to an iterator of a mutable type change the
> underlying object?

'i' is not an iterator, it is just a name

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

Assuming 'this' is 'change the contents of x'

for i in range(len(x)): x[i] = 2
# or
x = [2]*len(x)

Terry J. Reedy







More information about the Python-list mailing list