loop scope

Terry Reedy tjreedy at udel.edu
Thu Mar 11 18:03:23 EST 2004


"Arthur" <ajsiegel at optonline.com> wrote in message
news:f8k150pgq5ndk1q0s8s3vmgcusi7pl7b12 at 4ax.com...
>
> >>>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?

For loops with a break statement, the value of the loop index when the
break occurs may be the answer sought or needed to calculate it.  For list
comps which cannot have break, it is an artifact which may disappear in
2.4.

Terry J. Reedy







More information about the Python-list mailing list