no side effects

holger krekel pyth at devel.trillke.net
Wed Jan 8 08:48:03 EST 2003


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 am not against that (I am even in favor), but it fooled my 
> intuition coming from other languages.
> Maybe others will appreciate that.

One of the important things to know about python is the 
namespace concept.  In a namespace (be it local or global)
a name is bound to an object.  In

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

the for-loop will iteratively bind the (local) name to  
1, then 2, then 3.  It never looks at the binding of
the name 'i'.  With 'i=3' you only change the binding
of 'i' to the object '3' but the for-loop will blindly
change the binding again. 

To see the difference, in C, for example,  a name points 
to a memory location and 'i=3;' will do something to 
the memory location. 

Python's namespace abstraction is truly powerful although
sometimes surprising if you are used to thinking of 
'variables' and 'memory locations'. 

cheers,

    holger





More information about the Python-list mailing list