Simple question about mutable container iterator

Daniel 'Dang' Griffith noemail at noemail4u.com
Thu Apr 22 13:30:23 EDT 2004


On Thu, 22 Apr 2004 09:48:14 -0400, "Neal D. Becker"
<ndbecker2 at verizon.net> 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?
>
>2) What is the preferred way to do this?

I'm not sure what you're trying to do, and others have given ideas.
If you're trying to make x a list of 2's having the same length
as x had when you started, you could do this, and avoid the iteration:

x = [1,2,3]
x = len(x) * [2]

Or, if you're trying to set all elements to the average:

x = [1,2,3]
x = len(x) * [1.0 * sum(x) / len(x)]

Or, if you're trying to set all elements to the middle element:
x = [1,2,3]
x = len(x) * [x[len(x) / 2)]]

    --dang



More information about the Python-list mailing list