no side effects
Bengt Richter
bokr at oz.net
Wed Jan 8 10:52:23 EST 2003
On 8 Jan 2003 05:10:04 -0800, mis6 at pitt.edu (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.
I'm not sure what you mean by "side effect" here, but UIAM "i"
is effectively being bound/assigned-to as if something like this
was happening: (I changed your 3 to 4 to show final value effect)
>>> it = iter([1,2,3])
>>> try:
... while 1:
... i = it.next()
... print i,
... i=4
... except StopIteration:
... pass
...
1 2 3
>>> i
4
>>> for i in [1,2,3]:
... print i,
... i=4
...
1 2 3
>>> i
4
In other words, "i" is not part of the loop control conditions, but
it does get assigned to. The i=4 value doesn't get used at all,
as it's just overwritten by the next value from the iterator --
except when the StopIteration exception happens, which doesn't
assign anything to i, so leaves the last value assigned elsewhere alone.
Regards,
Bengt Richter
More information about the Python-list
mailing list