Incorrect scope of list comprehension variables

Brian Blais bblais at
Sun Apr 4 15:22:37 CEST 2010

On Apr 4, 2010, at 3:17 , Stephen Hansen wrote:

> Where exactly does this common sense come from? A list  
> comprehension is
> basically syntactic sugar over a for loop, and...

well, since I've been bitten by this particular wart, I was surprised  
to see that the list comp didn't have it's own scope.  If it's  
syntactic sugar for a for-loop, I figured that rather than converting

d = dict()
for r in [1,2,3]:
     d[r] = [r for r in [4,5,6]]


d = dict()
for r in [1,2,3]:

     for r in [4,5,6]:
     d[r] = L

it would convert it to something like:

d = dict()
for r in [1,2,3]:

     for _r in [4,5,6]:
     d[r] = L

still a for-loop, but without the surprising side-effect.  I'm glad  
they fixed this one!

surely, once you know, it's easy to overcome.  as a curiosity, I just  
went and skimmed the section:

which describes list comps, and didn't see any mention of this  
behavior.  it's probably there, but it certainly doesn't jump out.


Brian Blais
bblais at

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <>

More information about the Python-list mailing list