I think you misunderstood what an "iterator object" is. The for
loop is not an iterator object. For all goals and objectives, for the cycle as follows:
myList = [0, 1, 2, 3, 4] for x in myList: print x
does this (but more efficiently and less thoroughly):
i = 0 while i < len(myList) x = myList[i] print x i += 1
So, you see that any changes made to x
are lost as soon as the next cycle starts, because the value of x
overwritten by the value of the next element in the list.
As others have observed, you can change the value of a list during iteration over it. (But don't change its length! That's where you get into trouble.) One elegant way to do this is:
for i, x in enumerate(myList): myList[i] = some_func(x)
Update . It is also important to understand that copying is not performed in the for loop. In the above example, i
and x
- like all variables in Python - are more like pointers to C / C ++. As the loop progresses, the obj
points to myList[0]
, myList[1]
, etc., in turn. And like a C / C ++ pointer, the properties of the object that it points to do not change when the pointer changes. But just like a C pointer, you can directly change by pointing to a thing, because it is not a copy. In C, this is done by dereferencing a pointer; in Python, this is done using a mutable object. This is why NPE works. If i
and x
were even shallow copies, it would be impossible to do what he does.
The reason you cannot directly change the int
way of changing list
(as in NPE's answer) is because int
not changing. Once object 5
is created, nothing can change its meaning. Therefore, if passing around a pointer to 5
safe in Python - there can be no side effects, because the specified thing is immutable.