Are list comprehensions syntactic sugar for `list(generator expression)` in Python 3?

Both work differently. The list comprehension version takes advantage of the special bytecode LIST_APPEND which calls PyList_Append directly for us. Hence it avoids an attribute lookup to list.append and a function call at the Python level. >>> def func_lc(): [x**2 for x in y] … >>> dis.dis(func_lc) 2 0 LOAD_CONST 1 (<code object <listcomp> at … Read more

How exactly is Python Bytecode Run in CPython?

Yes, your understanding is correct. There is basically (very basically) a giant switch statement inside the CPython interpreter that says “if the current opcode is so and so, do this and that”. http://hg.python.org/cpython/file/3.3/Python/ceval.c#l790 Other implementations, like Pypy, have JIT compilation, i.e. they translate Python to machine codes on the fly.

Why does list ask about __len__?

See the Rationale section from PEP 424 that introduced __length_hint__ and offers insight on the motivation: Being able to pre-allocate lists based on the expected size, as estimated by __length_hint__ , can be a significant optimization. CPython has been observed to run some code faster than PyPy, purely because of this optimization being present. In … Read more

How references to variables are resolved in Python [duplicate]

In an ideal world, you’d be right and some of the inconsistencies you found would be wrong. However, CPython has optimized some scenarios, specifically function locals. These optimizations, together with how the compiler and evaluation loop interact and historical precedent, lead to the confusion. Python translates code to bytecodes, and those are then interpreted by … Read more