How do I convert a tuple of tuples to a one-dimensional list using list comprehension? [duplicate]

it’s typically referred to as flattening a nested structure. >>> tupleOfTuples = ((1, 2), (3, 4), (5,)) >>> [element for tupl in tupleOfTuples for element in tupl] [1, 2, 3, 4, 5] Just to demonstrate efficiency: >>> import timeit >>> it = lambda: list(chain(*tupleOfTuples)) >>> timeit.timeit(it) 2.1475738355700913 >>> lc = lambda: [element for tupl in … Read more

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 can I collect the results of a repeated calculation in a list, dictionary etc. (make a copy of a list with each element modified)?

General approaches There are three ordinary ways to approach the problem: by explicitly using a loop (normally a for loop, but while loops are also possible); by using a list comprehension (or dict comprehension, set comprehension, or generator expression as appropriate to the specific need in context); or by using the built-in map (results of … Read more

Why do list comprehensions write to the loop variable, but generators don’t? [duplicate]

Python’s creator, Guido van Rossum, mentions this when he wrote about generator expressions that were uniformly built into Python 3: (emphasis mine) We also made another change in Python 3, to improve equivalence between list comprehensions and generator expressions. In Python 2, the list comprehension “leaks” the loop control variable into the surrounding scope: x … Read more