Search code examples
pythonpython-2.7python-itertools

Combine a 2D array into 1D without numpy


The result of a list comprehension:

[['a', 'b', 'c'], ['ab', 'ac', 'bc'], ['abc']]

The challenge is to convert this into a single list, on one line, importing only itertools (if it helps)


Solution

  • The easy way is with itertools.chain.from_iterable:

    >>> import itertools
    >>> list(itertools.chain.from_iterable([['a', 'b', 'c'], ['ab', 'ac', 'bc'], ['abc']]))
    ['a', 'b', 'c', 'ab', 'ac', 'bc', 'abc']