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

Using while in list comprehension or generator expressions

Because the syntax of takewhile() and dropwhile() is not the clearest, here are the actual examples of your question: >>> [i for i in itertools.takewhile(lambda x: x*x<30, range(10))] [0, 1, 2, 3, 4, 5] >>> [i for i in itertools.dropwhile(lambda x: x*x<30, range(10))] [6, 7, 8, 9] Know that the author of itertools has questioned … Read more

yield in list comprehensions and generator expressions

Note: this was a bug in the CPython’s handling of yield in comprehensions and generator expressions, fixed in Python 3.8, with a deprecation warning in Python 3.7. See the Python bug report and the What’s New entries for Python 3.7 and Python 3.8. Generator expressions, and set and dict comprehensions are compiled to (generator) function … Read more

List comprehension vs generator expression’s weird timeit results?

Expanding on Paulo‘s answer, generator expressions are often slower than list comprehensions because of the overhead of function calls. In this case, the short-circuiting behavior of in offsets that slowness if the item is found fairly early, but otherwise, the pattern holds. I ran a simple script through the profiler for a more detailed analysis. … Read more