no side effects

"Martin v. Löwis" martin at v.loewis.de
Wed Jan 8 10:54:36 EST 2003


holger krekel wrote:
> Depends on your background.  *If* somebody e.g. thinks that 
> 
>     for i in range(3):
>         print i
>         i = 3
> 
> is somewhat equivalent to C's
> 
>     int i;
>     for (i=0 ; i<3 ; i++) {
>         printf("%d\n", i);
>         i = 3;
>     }
> 
> then IMHO my explanation serves well and talking about underlying 
> iterator protocols wouldn't help too much.  

Difficult to say, since you have to come up with a theory of why people 
think so. People might expect that the Python for loop translates to 
something like

seq = [1,2,3]
i = seq[0]
while 1:
   SUITE
   try:
     i = seq[seq.find(i)+1]
   except IndexError:
     break

Of course, they would never spell it out that way: they might think "At 
the end of the loop, look at the current value of i, then take the 
element from the sequence that follows i". This is roughly how the C 
loop works, and translates into the Python fragment above.

If the for loop would work that way, then the fact that Python has 
namespaces and variables bind to values wouldn't change the outcome of

for i in [1,2,3]:
   print i
   i = 3

I.e. i would be set to the last element of the sequence, and the for 
loop would look at where that element in the sequence is, and advance to 
the next element.

For loops *could* work that way, independent how variables and 
namespaces work. That they don't work this way comes from the hidden 
variable (which actually isn't even a variable, but a stack location - 
which is something else a newcomer shouldn't need to know).

> Why is the way the python for-loop gets to the next *value* 
> more important than understanding that python works with 
> name-object bindings everywhere?  And what is so wrong 
> about this (*)? 

I would expect that Michelle has grasped the notion of namespaces and 
name bindings by now; the question hinted at a misunderstanding of the 
for loop semantics. This details of the for loop is hardly ever noticed, 
but I'm sure it has confused more than one newcomer (I remember having 
been confused by it myself).

Regards,
Martin






More information about the Python-list mailing list