Incorrect scope of list comprehension variables
Steven D'Aprano
steve at REMOVE-THIS-cybersource.com.au
Sat Apr 17 10:27:02 EDT 2010
On Sat, 17 Apr 2010 12:05:03 +0200, Alain Ketterlin wrote:
>> I don't know of any language that creates a new scope for loop
>> variables, but perhaps that's just my ignorance...
>
> I think Pascal and Modula-2 do this, Fortran does this, as well as Ada.
Pascal doesn't do this.
[steve at sylar pascal]$ cat for_test.p
program main(input, output);
var
i: integer;
begin
for i := 1 to 3 do
begin
writeln(i);
end;
writeln(i);
end.
[steve at sylar pascal]$ gpc for_test.p
[steve at sylar pascal]$ ./a.out
1
2
3
3
However you can't assign to the loop variable inside the loop. Outside of
the loop, it is treated as just an ordinary variable and you can assign
to it as usual.
--
Steven
More information about the Python-list
mailing list