Incorrect scope of list comprehension variables

Alain Ketterlin alain at
Tue Apr 6 10:42:14 CEST 2010

Alain Ketterlin <alain at> writes:

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

Thanks to Chris and Paul for the details (the list comp. r actually
leaks). I should have found this by myself.

My background is more on functional programming languages, that's why I
thought the list comprehension iterator should be purely local. And yes,
I think a "classical" for-loop iterator should also be local to the
loop, but I understand this may be too counter-intuitive to many :-)

-- Alain.

More information about the Python-list mailing list