Unexpected result.

Larry Bates lbates at swamisoft.com
Thu Sep 23 15:18:01 EDT 2004


Actually the result is exactly as expected.
Programming 101 teaches us not to reuse
loop variables in nested loops.

and

People have enough problems with "scope"
already (just monitor this newsgroup for
a while if you don't believe me).  Also
consider a variation of your example:

d={}
for i in ('a','b','c'):
    for j in (1,2,3):
        d[i]=j

If 'j' loop had local scope how could
it reference 'i'?

Larry Bates


"Grzegorz Dostatni" <grzegorz at ee.ualberta.ca> wrote in message 
news:Pine.LNX.4.44.0409231312490.8517-100000 at e5-05.ee.ualberta.ca...
>
> Consider the following fragment:
>
>>>> for i in ('a','b','c'):
> ...     for i in (1,2,3):
> ...             print i,
> ...     print i,
> ...
> 1 2 3 3 1 2 3 3 1 2 3 3
>
> Now. I believe I know what is happening. The i in both loops refers to the
> same variable. My question is whether it would make more sense (be more
> intuitive) to have a for loop create its own local scope. (ie. an output
> string of
> 1 2 3 a 1 2 3 b 1 2 3 c
>
> )
>
> Grzegorz
>
>
> "Some cause happiness wherever they go; others, whenever they go."
> - Oscar Wilde (1854-1900)
>
> 





More information about the Python-list mailing list