no side effects

Cliff Wells LogiplexSoftware at earthlink.net
Wed Jan 8 19:37:39 CET 2003


On Wed, 2003-01-08 at 05:10, 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.

You've gotten a lot of detailed responses, but maybe this will make it
clearer:

_l = [1,2,3]
for _i in range(len(_l)):
    i = _l[_i]
    print i,
    i = 3 


In this case you obviously wouldn't expect assigning 3 to i to change
the loop, yet this is similar to what is happening in the case you
presented, except that _i is created implicitly by the interpreter and
is hidden from normal Python programs.

Regards,

-- 
Cliff Wells, Software Engineer
Logiplex Corporation (www.logiplex.net)
(503) 978-6726 x308  (800) 735-0555 x308






More information about the Python-list mailing list