loop scope

Arthur ajsiegel at optonline.com
Fri Mar 12 09:06:38 EST 2004


On Thu, 11 Mar 2004 17:54:56 -0700, David MacQuigg <dmq at gain.com>
wrote:
>>
>>>>> b=[4,5,6]
>>>>> [t*2 for t in b]
>>[8, 10, 12]
>>>>> t
>>6
>>
>>Is this anywhere useful, or more of an artifact?
>
>Scopes are defined by the boundaries of functions, classes and
>modules, not for loops.  This is essential, or you would have to
>declare global variables inside most for loops.

I am not following this argument.  The surprise, specifically,  is
that I don't think of myself as having declared "t" as a variable.  it
is don't magically, as a placeholder and for a very specific purpose.
So I would expect it to go away outside of the " [ " and " ] " by
equal and opposite magic.

I ran into the issue while playing at the prompt.  Running the same
statement I had run previously gave me a different result than before.
Surprising.  Yes I had tested a list comp, in between.  Because I have
been around the language for some time, and have my ear to the ground,
it didn't take me long to understand what was happening. 

Flabbergasted, rather than surprised, might have otherwise been the
reaction.

Art




More information about the Python-list mailing list