Incorrect scope of list comprehension variables

MRAB python at
Sat Apr 17 02:58:29 CEST 2010

Steven D'Aprano wrote:
> On Fri, 16 Apr 2010 08:48:03 -0700, Aahz wrote:
>> In article <4bb92850$0$8827$c3e8da3 at>, Steven D'Aprano 
>> <steve at> 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...
The programming language Ada comes to mind (the variable exists only
within the body of the loop and is read-only like a constant), so yes,
that's just your ignorance. ;-)

More information about the Python-list mailing list