no side effects
andy at eastonwest.co.uk
Fri Jan 10 23:02:18 CET 2003
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
> _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.
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
p+=1 # increment loop control counter
Or am I missing the point completely?
More information about the Python-list