Incorrect scope of list comprehension variables
no.email at nospam.invalid
Sun Apr 4 17:50:54 EDT 2010
Alain Ketterlin <alain at dpt-info.u-strasbg.fr> writes:
> d[r] = [r for r in [4,5,6]]
> THe problem is that the "r" in d[r] somehow captures the value of the
> "r" in the list comprehension, and somehow kills the loop interator.
Yes, this is a well known design error in Python 2.x. The 3.x series
fixes this error but introduces other errors of its own. It is evil
enough that I almost always use this syntax instead:
d[r] = list(r for r in [4,5,6])
that works in 3.x and the later releases of 2.x. In early 2.x (maybe up
to 2.2) it throws an error at compile time rather than at run time.
More information about the Python-list