no side effects

Antonio Cuni cuniREMOVE_THIS at programmazione.it
Thu Jan 9 00:25:02 CET 2003


Michele Simionato wrote:

> I was surprised by the following code:
> 
>>>> for i in [1,2,3]:
> ...     print i,
> ...     i=3
> 
> I would have expected only 1 to be printed, but instead Python
> continues the loop without noticing that the value of i has
> changed. IOW, no side effect.

If you looks at the while+iterator equivalent of for loops you won't be 
surprised any more:

_hidden_iterator = iter([1,2,3])
while 1:
    try: i = _hidden_iterator.next()
    except StopIteration: break 
    print i,
    i = 3

Your for loop is semantically equivalent to my code above: you can easily 
see why there are "no side effects"

ciao Anto
-- 
"Computer science is not about computers any more than astronomy
is about telescopes." -- EW Dijkstra





More information about the Python-list mailing list