variable scope in list comprehensions
Duncan Booth
duncan.booth at invalid.invalid
Fri Apr 4 04:57:42 EDT 2008
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.
For the OP, in some languages (e.g. C) 'for' loops typically calculate
the value of the loop control variable based on some expression
involving the previous value. Python isn't like that. In Python the data
used to compute the next value is stored internally: you cannot access
it directly.
That means you can reassign or delete the loop control variable if you
want, but it doesn't affect the loop iteration; every time round the
loop there is a fresh assignment to the variable.
So the code:
for y in range(8):
for y in range(8):
pass # or whatever the body of the loops
is sort of equivalent to:
__loop_control_1__ = iter(range(8))
while True:
try:
y = __loop_control_1__.next()
except StopIteration:
break
__loop_control_2__ = iter(range(8))
while True:
try:
y = __loop_control_1__.next()
except StopIteration:
break
pass # or whatever the body of the loops
except there are no accessible variables __loop_control_1__ or
__loop_control_2__.
More information about the Python-list
mailing list