no side effects

Cliff Wells LogiplexSoftware at earthlink.net
Fri Jan 10 17:48:34 EST 2003


On Fri, 2003-01-10 at 14:02, andy wrote:
> On Wednesday 08 Jan 2003 6:37 pm, Cliff Wells wrote:
> > 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,
> 
> Has to be noted, also, that many other languages would exhibit either the same 
> behaviour or even random effects, due to loop optimizations, such as keeping 
> the loop variable in a machine register, or even unfolding the loop.  But in 
> any case, most languages' /for/ loop iterates over a sequence of ordinals, 
> not a list...
> 
> isn't it more like this?
> 
> p=0 # internal loop counter
> lst=[1,2,3] # the list to enumerate
> while p<len(lst): # control loop
>     i=lst[p] # get the current list item
>     print i
>     i=3
>     p+=1 # increment loop control counter
> 
> Or am I missing the point completely?

I think we're saying the same thing.  I just chose to get my indices by
using range whereas you explicitly increment it.  Yours is probably
closer to what other languages do, since it would allow you to change p
and affect the loop, whereas mine would continue merrily on =)

-- 
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