Simple question about mutable container iterator

N

Neal D. Becker

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?
 
D

Diez B. Roggisch

Neal said:
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
 
D

Daniel 'Dang' Griffith

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
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,186
Messages
2,570,998
Members
47,587
Latest member
JohnetteTa

Latest Threads

Top