no side effects
"Martin v. Löwis"
martin at v.loewis.de
Wed Jan 8 09:13:48 EST 2003
holger krekel wrote:
> for i in [1,2,3]:
> print i
> i=3
>
> the for-loop will iteratively bind the (local) name to
> 1, then 2, then 3. It never looks at the binding of
> the name 'i'. With 'i=3' you only change the binding
> of 'i' to the object '3' but the for-loop will blindly
> change the binding again.
This has nothing to do with namespaces: i is not local to the for loop,
but might be global, or local to the function.
More relevant is that each for loop introduces a hidden variable. This
hidden variable used to be an index into the sequence iterated over, and
now is an iterator object which draws the next element from the sequence.
> To see the difference, in C, for example, a name points
> to a memory location and 'i=3;' will do something to
> the memory location.
The equivalent loop in C(++) would be
for(iterator_type iterator=sequence.begin();
iterator != sequence.end(); iterator++){
i = *iterator;
print i;
i = 3;
}
There is no way to access the hidden variable in Python.
Regards,
Martin
More information about the Python-list
mailing list