Skip to content Skip to sidebar Skip to footer

Why The List Comprehension Variable Is Accessible After The Operation Is Done?

As part of another experience i encountered a problem in the list comprehension. In order to put simply, if I am trying the following code: m = [ k**2 for k in range(7)] print m

Solution 1:

Because in Python 2, the list variable 'leaks' to the surrounding scope. This was a mistake in the way list comprehensions were built.

This has been corrected for dict and set comprehensions, generator expressions and in Python 3 for list comprehensions as well.

It is not a memory leak. It's just an error in the scope of the variable.

Solution 2:

No, it's not a memory leak as that term is usually defined. In Python 2.x, a list comprehension is not a separate scope, so a variable you use in a list comprehension is in the scope of the function that contains it. You can easily see this in action by setting kbefore the list comprehension; the listcomp will clobber it.

Because a valid reference exists, the object k points to is (properly) not garbage collected.

In Python 3.x, this was changed; all comprehensions create their own scopes and do not "leak" into the enclosing scope.

In Python 2.x, generator expressions do have their own scope, however, so if you want that behavior, just write it like this:

m = list(k**2 for k in range(7))

Post a Comment for "Why The List Comprehension Variable Is Accessible After The Operation Is Done?"