Why is the list comprehension variable available after the operation is completed?

As part of another experience, I ran into a problem understanding the list. To just say if I try to execute the following code:

m = [ k**2 for k in range(7)] print m [0, 1, 4, 9, 16, 25, 36] print k 6 
  • My question is: how can python get the value k, outside the list comprehension?
  • Why is there no garbage collection?
  • Is this not a memory leak?
+2
python list-comprehension
May 17 '13 at 15:17
source share
2 answers

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)) 
+4
May 17 '13 at 15:20
source share

Since in Python 2 the list variable is "leaked" to the surrounding volume. This was a mistake in how the listing methods were built.

This has been fixed for dict and given concepts, generator expressions, and in Python 3 for list comprehension.

This is not a memory leak. This is simply a mistake in the scope of a variable.

+9
May 17 '13 at 15:19
source share



All Articles