As a byproduct of wandering about how list views are implemented, I found a good answer to your question.
In Python 2, take a look at the bytecode generated for a simple list comprehension:
>>> s = compile('[i for i in [1, 2, 3]]', '', 'exec') >>> dis(s) 1 0 BUILD_LIST 0 3 LOAD_CONST 0 (1) 6 LOAD_CONST 1 (2) 9 LOAD_CONST 2 (3) 12 BUILD_LIST 3 15 GET_ITER >> 16 FOR_ITER 12 (to 31) 19 STORE_NAME 0 (i) 22 LOAD_NAME 0 (i) 25 LIST_APPEND 2 28 JUMP_ABSOLUTE 16 >> 31 POP_TOP 32 LOAD_CONST 3 (None) 35 RETURN_VALUE
it essentially translates into a simple for-loop that uses syntactic sugar for it. As a result, the same semantics are used as for for-loops :
a = [] for i in [1, 2, 3] a.append(i) print(i)
In the case of list comprehension (C), Python uses the "hidden list name" and the special LIST_APPEND command to handle the creation, but actually does nothing.
So, your question should generalize to why Python writes a for loop variable to for-loop s; it's nice to reply to a blog post from Eli Benderski .
Python 3, as already mentioned, and others, has changed the semantics of list comprehension to better fit the structure of generators (by creating a separate code object for understanding) and is essentially syntactic sugar for the following:
a = [i for i in [1, 2, 3]]
this will not leak because it does not start in the very top area, as the Python 2 equivalent does. i only filters in __f and then is destroyed as a local variable for this function.
If you want, look at the bytecode generated for Python 3, at dis('a = [i for i in [1, 2, 3]]') . You will see how the "hidden" code object is loaded, and then the function call ends.