variable scope in list comprehensions

Steve Holden steve at holdenweb.com
Thu Apr 3 22:39:22 EDT 2008


Piotr Sobolewski wrote:
> Hello,
> 
> there is something I don't understand about list comprehensions.
> 
> I understand how does this work:
> print [[y for x in range(8)] for y in range(8)]
> 
> However I don't understand why this one works:
> print [[y for y in range(8)] for y in range(8)]
> 
> In this second example I have one loop nested in another. Both loops uses
> the same variable - y. How is it that those loops do not conflict with each
> other?
> 
> For a moment I thought that maybe list comprehension has its own scope, but
> it doesn't seem to be so:
> print [[y for y in range(8)] for y in range(8)]
> print y
> 
> Does anybody understand it?
> 
> 
This isn't _a_ list comprehension, it's *two* list comprehensions. The 
interpreter computes the value if the inner list comprehension and then 
duplicates eight references to it (as you will see if you change an 
element).

Why do you think the two scopes would interfere anyway? The outer loop's 
control variable is never used in the inner loop, so there is no chance 
of conflict: each time the inner loop terminates the outer loop assigns 
the next value from its range - it isn't "adding one" to the variable, 
but merely calling an iterator's next() method.

regards
  Steve
-- 
Steve Holden        +1 571 484 6266   +1 800 494 3119
Holden Web LLC              http://www.holdenweb.com/




More information about the Python-list mailing list