Incorrect scope of list comprehension variables

Alain Ketterlin alain at
Sat Apr 17 06:05:03 EDT 2010

Steven D'Aprano <steve at> writes:

> On Fri, 16 Apr 2010 08:48:03 -0700, Aahz wrote:
>>>Nevertheless, it is a common intuition that the list comp variable
>>>should *not* be exposed outside of the list comp, and that the for-loop
>>>variable should. Perhaps it makes no sense, but it is very common --
>>>I've never heard of anyone being surprised that the for-loop variable is
>>>exposed, but I've seen many people surprised by the fact that list-comps
>>>do expose their loop variable.
>> I've definitely seen people surprised by the for-loop behavior.
> What programming languages were they used to (if any)?
> I don't know of any language that creates a new scope for loop variables, 
> but perhaps that's just my ignorance...

I think Pascal and Modula-2 do this, Fortran does this, as well as Ada.
I'm sure derivatives of Ada like Oracle's PL/SQL also enforce this. And
of course C/C++/Java if the programmer wants it that way. Actually I
think C was the first to consider "for" as some kind of syntactic sugar
for "while" (thus blurring the notion of a for-loop forever). Python's
for is really a member of the for-each family.

May I add that having strict for-loop iterators is a good thing, at
least in languages like C/C++/Fortran/etc. Optimizing compilers usually
spend some time detecting so-called "induction variables" when they're
not given: it helps simplifying loop bodies, it reduces register
pressure, and changes many array accesses into pointer increments, among
other things.

-- Alain.

More information about the Python-list mailing list