Search code examples
pythonpython-3.xiterable-unpackingpeppep448

Additional Unpacking Generalizations (PEP 448) with variable number of elements


The acceptance of PEP 448 has introduced Additional Unpacking Generalizations in Python 3.5.

For example:

>>> l1 = [1, 2, 3]
>>> l2 = [4, 5, 6]

# unpack both iterables in a list literal
>>> joinedList = [*l1, *l2]
>>> print(joinedList)
[1, 2, 3, 4, 5, 6]

QUESTION: Is there a way to do similar thing with a list of lists?

This code does not work:

SyntaxError: iterable unpacking cannot be used in comprehension

# List of variable size
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
joined_list = [*l for l in list_of_lists]

Of course, you could do the following but that looks less elegant and does not look efficient:

# List of variable size
list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
joined_list = list()
for l in list_of_lists:
    joined_list += l

Solution

  • How about going old school: sum()

    Code:

    joined_list = sum(list_of_lists, [])
    

    Test Code:

    # List of variable size
    list_of_lists = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
    joined_list = sum(list_of_lists, [])
    print(joined_list)
    

    Results:

    [1, 2, 3, 4, 5, 6, 7, 8, 9]