No, this is not a memory leak, as this term is usually defined. In Python 2.x, list comprehension is not a separate area, so the variable that you use in list comprehension falls within the scope of the function that contains it. You can easily see this in action by setting k before understanding the list; listcomp will compress it.
Since a valid link exists, the k object points to (correctly), not to garbage collection.
In Python 3.x, this has been changed; all understandings create their own areas and do not "flow" into the covering area.
In Python 2.x, generator expressions have their own scope, so if you want this behavior, simply write it like this:
m = list(k**2 for k in range(7))
kindall May 17 '13 at 15:20 2013-05-17 15:20
source share