By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
443,846 Members | 1,872 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 443,846 IT Pros & Developers. It's quick & easy.

Simple question about mutable container iterator

P: n/a
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?
Jul 18 '05 #1
Share this Question
Share on Google+
2 Replies


P: n/a
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
Jul 18 '05 #2

P: n/a
On Thu, 22 Apr 2004 09:48:14 -0400, "Neal D. Becker"
<nd*******@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
Jul 18 '05 #3

This discussion thread is closed

Replies have been disabled for this discussion.