variable scope in list comprehensions
Steve Holden
steve at holdenweb.com
Sat Apr 5 08:44:13 EDT 2008
Duncan Booth wrote:
> Steve Holden <steve at holdenweb.com> wrote:
>
>>> 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).
>>
> Do you want to reconsider that statement? The interpreter recomputes the
> inner list comprehension eight times, there are no duplicated
> references.
>
[...]
You are correct. I wrote that before testing, and then after testing
wrote """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."""
So I didn't do enough editing after testing to (in)validate my
preconceptions.
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