loop scope

David MacQuigg dmq at gain.com
Thu Mar 11 19:54:56 EST 2004


On Thu, 11 Mar 2004 21:08:09 GMT, Arthur <ajsiegel at optonline.com>
wrote:

>
>>>>a=[1,2,3]
>>>> for p in a:
>	print p
>1
>2
>3
>>>> p
>3
>
>My naive expectation was that p would be 'not defined' from outside
>the loop.
>
>I know this is not news. 
>
>In fact I had come across some discussion of this fact, but apparently
>didn't register it.
>
>As I got myself surprised by it - specifically  in the context of list
>comps, where I think it is particularly surprising:
>
>>>> 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.

For a good, up-to-date discussion of scopes, see Learning Python, Ch.
13 Scopes and Arguments, and p.337 - Namespaces: The Whole Story.  Be
sure to get the 2nd edition.  The scope rules have changed
significantly since the first edition.

-- Dave




More information about the Python-list mailing list